• 编译器自动调用
  • 无返回值
  • 函数名 与 类名一致
  • 可多个构造函数 - 重载
  • 程序在调用对象的时候会自动调用 , 无需手动 , 单一个类的创建只会调用一次 ```cpp class Student{ public: //无参构造 Student(){};

    //有参构造 Student(int a){};

    //拷贝构造函数 Student(Student& stu){ } };

int main(){ //显示转换 Student stu; // Student stu();为错误写法 , 系统会以为这是函数声明 Student stu(10);

  1. //隐式转换
  2. Student stu = 10; // 等于 Student stu = Student(10);

}

  1. ---
  2. <a name="FIWB8"></a>
  3. ### 拷贝函数
  4. - 深拷贝 / 浅拷贝
  5. - 系统默认创建的是浅拷贝
  6. - 深拷贝: 在堆区重新开辟一块空间, 然后在赋值
  7. ```cpp
  8. class Student{
  9. int age;
  10. int * height;
  11. //深拷贝
  12. Student(const Student& stu){
  13. this.age = stu.age;
  14. //浅拷贝做法: this.height = stu.height;
  15. this.height = new int(*stu.height);
  16. }
  17. ~Student(){
  18. if(this.height != NULL){
  19. delete height;
  20. }
  21. }
  22. }

初始化列表

  1. #include <iostream>
  2. using namespace std;
  3. class Student {
  4. public:
  5. int a;
  6. int b;
  7. int c;
  8. Student(int aa, int bb, int cc): a(aa), b(bb), c(cc) {};
  9. Student() {};
  10. };
  11. int main() {
  12. Student stu(10,20,30);
  13. cout << "a:" << stu.a << endl;
  14. cout << "b:" << stu.b<< endl;
  15. cout << "c:" << stu.c << endl;
  16. return 0;
  17. }