重载赋值操作符
C++默认的赋值操作是按成员赋值,一些情况下(如含有指针成员时),这种操作往往会有问题。如:
1 #include "stdafx.h" 2 #include <string> 3 4 using namespace std; 5 6 class A 7 { 8 private: 9 char *p; 10 size_t nSize; 11 public:A(const string &str); 12 ~A(); 13 }; 14 15 A::A(const string &str) 16 { 17 nSize = str.size(); 18 p = new char[nSize + 1]; 19 strcpy_s(p,nSize+1,str.c_str()); 20 p[nSize] = '\0'; 21 } 22 23 A::~A() 24 { 25 delete[] p; 26 } 27 28 int _tmain(int argc, _TCHAR* argv[]) 29 { 30 { 31 A obj1("hello"); 32 A obj2("world"); 33 obj2 = obj1;//赋值操作 34 } 35 system("pause"); 36 return 0; 37 }
编译,运行会出错
原因是赋值操作后,obj1.p和obj2.p指向了同一块内存,如下所示。
析构时就对同一块内存释放了两次。
我们赋值的真正意思可能是,两个对象各有自己的一块内存,互不相干,只是复制其中的内容。这时候就需要重载赋值操作符了。
1 #include "stdafx.h" 2 #include <string> 3 4 using namespace std; 5 6 class A 7 { 8 private: 9 char *p; 10 size_t nSize; 11 public: 12 A& operator=(const A &a);//重载赋值操作符 13 public: 14 A(const string &str); 15 ~A(); 16 }; 17 18 A::A(const string &str) 19 { 20 nSize = str.size(); 21 p = new char[nSize + 1]; 22 strcpy_s(p,nSize+1,str.c_str()); 23 p[nSize] = '\0'; 24 } 25 26 A::~A() 27 { 28 delete[] p; 29 } 30 31 inline A& A::operator=(const A &a) 32 { 33 if (&a != this)//防止自赋值 34 { 35 delete[] p; 36 p = new char[a.nSize + 1]; 37 strcpy_s(p,nSize+1,a.p); 38 } 39 return *this; 40 } 41 42 int _tmain(int argc, _TCHAR* argv[]) 43 { 44 { 45 A obj1("hello"); 46 A obj2("world"); 47 obj2 = obj1;//赋值操作 48 } 49 system("pause"); 50 return 0; 51 }
运行结果
注:若不希望用户对该类对象进行赋值操作,则可以重载赋值操作符为private。