构造函数、析构函数、初始化列表
class Demo { public: Demo(){} Demo(string name, int age){ m_strName = name; m_iAge = age; } //构造函数可以重载 private: string m_strName; int m_iAge; }; class Demo { public: Demo(){} Demo(string name = "James", int age = 24){ m_strName = name; m_iAge = age; } //构造函数形参列表可以赋初值,但这种情况不行,全部赋初值会与前面的无参构造函数冲突 private: string m_strName; int m_iAge; }; class Demo { public: Demo(){} Demo(string name, int age):m_strName(name),m_iAge(age){} //初始化列表,可用于初始化const修饰的 //成员变量,初始化列表先于构造函数执行,效率高 private: const string m_strName; const int m_iAge; };
class Demo { public: Demo(){} Demo(string name, int age):m_strName(name),m_iAge(age){}
Demo(const Demo &demo){} //复制(拷贝)构造函数,形参是const修饰的自身类的对象的引用,当对象作为值传递时,发生调用
//比如同类型的一个对象给另一个对象赋值、对象作为函数的形参,函数被调用
private: const string m_strName; const int m_iAge; };
~Demo(){} //析构函数,无返回值、无形参,不能重载,对象销毁时自动调用
class Demo { public: Demo(){m_iCount = 5;m_pDemo = new int[m_iCount];} Demo(string name, int age):m_strName(name),m_iAge(age){} Demo(const Demo &demo) { m_strName = demo.m_strName; m_iAge = demo.m_iAge; m_iCount = demo.m_iCount; m_pDemo = demo.m_pDemo; //浅拷贝,此时复制构造函数只是简单地将成员变量一一赋值给新的对象的成员变量,可以看出两个对象的指针m_pDemo将指向同一块内存,这样将导致重复赋值、重复销毁内存的严重问题 } private: string m_strName; int m_iAge; int m_iCount; int *m_pDemo; } int main() { Demo demo1; Demo demo2 = demo1; return 0; }
class Demo { public: Demo(){m_iCount = 5;m_pDemo = new int[m_iCount];} Demo(string name, int age):m_strName(name),m_iAge(age){} Demo(const Demo &demo) { m_strName = demo.m_strName; m_iAge = demo.m_iAge; m_iCount = demo.m_iCount; m_pDemo = new int[m_iCount]; //深拷贝,新申请一块内存,避免重复指向同一块内存 for(int i = 0; i < m_iCount; i++) { m_pDemo[i] = demo.m_pDemo[i]; //新申请的内存中的数据依次接收原对象的赋值,这种不是简单的值拷贝,而是堆中数据也依次拷贝的方式叫做深拷贝 } } private: string m_strName; int m_iAge; int m_iCount; int *m_pDemo; } int main() { Demo demo1; Demo demo2 = demo1; return 0; }