赋值运算符=重载
operator=(){}
c++编译器至少给一个类添加4个函数
1、默认构造函数(无参,函数体为空)
2、默认析构函数(无参,函数体为空)
3、默认拷贝函数 (对属性将进行只拷贝)
4、赋值运算符operator=对值进行只拷贝
如果类中有属性指向堆区做赋值操作也会出现浅拷贝问题
1 #include<iostream> 2 using namespace std; 3 class Persion 4 { 5 public: 6 Persion(int a) 7 { 8 m_A = new int(a);//在堆区开辟空间 9 } 10 ~Persion() 11 { 12 if (m_A != NULL) 13 { 14 delete this->m_A; 15 m_A = NULL; 16 } 17 } 18 Persion& operator=(Persion &p)//赋值符=重载 19 { 20 if (m_A != NULL) 21 { 22 delete this->m_A; 23 p.m_A - NULL; 24 } 25 m_A = new int(*p.m_A); 26 return *this; 27 } 28 int *m_A; 29 }; 30 ostream& operator<<(ostream &cout,Persion &p1) // 31 { 32 cout << *p1.m_A; 33 return cout; 34 35 } 36 int main() 37 { 38 Persion p1(10); 39 Persion p2(20); 40 Persion p3(30); 41 p3 = p2 = p1; 42 cout << p1 << endl; 43 cout << p2 << endl; 44 cout << p3 << endl; 45 system("pause"); 46 return 0; 47 }
原文:https://www.cnblogs.com/putobit/p/14410254.html