- 编译器自动调用
- 无返回值
- 函数名 与 类名一致
- 可多个构造函数 - 重载
程序在调用对象的时候会自动调用 , 无需手动 , 单一个类的创建只会调用一次 ```cpp class Student{ public: //无参构造 Student(){};
//有参构造 Student(int a){};
//拷贝构造函数 Student(Student& stu){ } };
int main(){ //显示转换 Student stu; // Student stu();为错误写法 , 系统会以为这是函数声明 Student stu(10);
//隐式转换Student stu = 10; // 等于 Student stu = Student(10);
}
---<a name="FIWB8"></a>### 拷贝函数- 深拷贝 / 浅拷贝- 系统默认创建的是浅拷贝- 深拷贝: 在堆区重新开辟一块空间, 然后在赋值```cppclass Student{int age;int * height;//深拷贝Student(const Student& stu){this.age = stu.age;//浅拷贝做法: this.height = stu.height;this.height = new int(*stu.height);}~Student(){if(this.height != NULL){delete height;}}}
初始化列表
#include <iostream>using namespace std;class Student {public:int a;int b;int c;Student(int aa, int bb, int cc): a(aa), b(bb), c(cc) {};Student() {};};int main() {Student stu(10,20,30);cout << "a:" << stu.a << endl;cout << "b:" << stu.b<< endl;cout << "c:" << stu.c << endl;return 0;}
