# 类

类在 C++ 中非常重要，踏实下心来，梳理一下类的相关知识，是非常有必要的

```cpp
#include <iostream>

int main() 
{
    int a;
    std::cout << a << std::endl;
    return 0;
}
```

这时会提示报错：使用了未初始化的局部变量 “a”

* Class0：类的声明里写了`Class0();`语句，但没有写实现。报错：无法解析的外部命令
* Class1：类的声明里写了`Class1();`语句，实现写了一个空函数。正常，输出0
* Class2：类的声明里不写`Class2();`语句。正常，输出0
* Class3：类的声明里写了`Class3()=default;`语句，但没有写实现。正常
* Class4：类的声明里写了`Class4()=default;`语句，自己又写了实现。报错：函数已有主体

默认构造函数 = 声明+空实现 = 不声明 = 声明+default

我们以Class3为例，

* Class3 a3; 正常
* Class3 a31(); 这是声明了个函数
* Class3 a32 = Class3(); 创建了一个`Class3`的临时对象，并使用它来初始化`a32`
* Class3 a33{}; 这种语法是统一初始化语法（Uniform Initialization），从C++11开始引入

拷贝构造函数在以下情况下会被调用：

* 使用一个对象初始化另一个对象。
* 将对象作为参数传递给函数（按值传递）。
* 函数按值返回对象。

#### 触发赋值操作符

赋值操作符在以下情况下会被调用：

* 一个已存在的对象被赋值为另一个对象。

```cpp
#include <iostream>
#include "Class1.h"

int main() 
{
    Class1 a;
    std::cout << a.age << std::endl;
    return 0;
}

#include <memory>

class Class1
{
public:
    Class1();
    int age;
    double height;
    std::shared_ptr<int> grade;
};

#include "Class1.h"

Class1::Class1()
{

}
```

这时候会提示未初始化变量，但程序可以编译，会输出一个乱值

```cpp
Class1::Class1()
{
	age = 17;
	height = 1.8;
}
```

如果我这样修改，即使我没有给指针变量赋值，也不会提醒我

```cpp

class Person
{
    public:
     Person();
    private:
     int age;
     std::string name;
};
```

## 构造函数

构造函数是一种特殊的成员函数，其函数名与类的名相同，在创建对象时被调用，用于初始化对象的成员变量和执行其他的一些自定义操作


---

# Agent Instructions: Querying This Documentation

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

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://tysun.gitbook.io/c++/lei.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
