> For the complete documentation index, see [llms.txt](https://docs.1l.lol/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.1l.lol/oop/classes.md).

# 面向对象与类

### 面向对象思想

面向对象（OOP）把数据和操作数据的方法封装在一起，形成**对象**。三大特性：

* **封装**：隐藏内部细节，只暴露必要接口
* **继承**：子类复用父类的属性和方法
* **多态**：同一接口有不同实现

### 类的定义与创建

```cpp
#include <iostream>
using namespace std;

class Student {
private:                  // 私有成员，外部不可直接访问
    string name;
    int score;

public:
    Student(string n, int s) : name(n), score(s) {}  // 构造函数

    void print() {        // 成员函数
        cout << name << " " << score << endl;
    }

    int getScore() { return score; }
};

int main() {
    Student a("Tom", 95); // 创建对象
    a.print();
    return 0;
}
```

### 访问权限

| 关键字         | 说明          |
| ----------- | ----------- |
| `private`   | 仅类内部可访问（默认） |
| `public`    | 任何地方可访问     |
| `protected` | 类内部及子类可访问   |

### 继承

```cpp
class Person {
public:
    string name;
    void hello() { cout << "I am " << name << endl; }
};

class Student : public Person {   // 继承
public:
    int grade;
};
```

### 多态（虚函数）

```cpp
class Animal {
public:
    virtual void speak() { cout << "..." << endl; }
};
class Dog : public Animal {
public:
    void speak() override { cout << "Woof" << endl; }
};
```

### 要点

* 构造函数与类同名、无返回值，用于初始化对象。
* 封装让数据更安全，继承让代码可复用，多态让程序更灵活。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.1l.lol/oop/classes.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
