C++编译器至少给一个类添加4个函数
默认构造函数(无参,函数体为空)
默认析构函数(无参,函数体为空)
默认拷贝构造函数,对属性进行值拷贝(形参:const 类名 &obj)
赋值运算符operator=,对属性进行值拷贝
如果类中有属性指向堆区,做赋值操作时也会出现深浅拷贝问题
//赋值运算符重载class Person{public:Person(int age){m_age = new int(age);}//重载 赋值运算符Person &operator=(Person& p){//编译器提供的拷贝操作//m_age = p.m_age;//应该先判断是否有属性在堆区,如果有先释放干净,然后再深拷贝if (m_age != nullptr){delete m_age;m_age = nullptr;}//深拷贝m_age = new int(*p.m_age);return *this;}~Person(){if (m_age != nullptr){delete m_age;m_age = nullptr;}}int* m_age;};void test01(){Person p1(18);Person p2(20);Person p3(30);p3 = p2 = p1;cout << "P1的年龄是:" << *p1.m_age << endl;cout << "P2的年龄是:" << *p2.m_age << endl;cout << "P3的年龄是:" << *p3.m_age << endl;}int main(){test01();int a = 10;int b = 20;int c = 30;c = b = a;cout << "a = " << a << endl;cout << "b = " << b << endl;cout << "c = " << c << endl;system("pause");return 0;}
