注意: C++中, 重载赋值运算符函数 只能作为类的成员函数
c++编译器至少给一个类添加4个函数
- 默认构造函数(无参,函数体为空)
 - 默认析构函数(无参,函数体为空)
 - 默认拷贝构造函数,对属性进行值拷贝
 - 赋值运算符 operator=, 对属性进行值拷贝
 
如果类中有属性指向的是堆区,那么做赋值操作的时候也会出现深浅拷贝的问题。
而编译器给我们提供的赋值运算进行的是浅拷贝,深拷贝需要我们手动写代码实现
代码
class Person{public:Person(int age){//将年龄数据开辟到堆区m_Age = new int(age);}//重载赋值运算符Person& operator=(Person &p){if (m_Age != NULL){delete m_Age;m_Age = NULL;}//编译器提供的代码是浅拷贝//m_Age = p.m_Age;//提供深拷贝 解决浅拷贝的问题m_Age = new int(*p.m_Age);//返回自身return *this;}~Person(){if (m_Age != NULL){delete m_Age;m_Age = NULL;}}//年龄的指针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;}
