#include<string.h> #include<iostream> using namespace std; class test{ public: test(char *p ){ cout << "this is construction of test"<< p << endl; if(p){ pData = new char[strlen(p)+1]; strcpy(pData, p ); } else { pData = new char[1]; *pData = '\0'; } } test(const test & T){ cout <<" this is copy construction of test " << T.pData<< endl; if(T.pData){ pData = new char [strlen(T.pData)+1]; strcpy( pData , T.pData); } else { pData = new char [1] ; *pData = '\0'; } } test &operator = (const test & T){ cout << "this is operator = :" << pData <<"=" << T.pData << endl ; if(this == &T) return *this; if(T.pData) { if(pData){ delete [] pData; } pData = new char [strlen(T.pData) + 1]; strcpy(pData , T.pData); } else { pData = new char[1]; *pData = '\0'; } return * this; } ~test(){ cout << "this is dectruction of test "<< pData << endl ; delete [] pData; } void set( char*value) { if(value) { delete [] pData; pData = new char [strlen(value) + 1]; strcpy(pData , value); } else { pData = new char[1]; *pData = '\0'; } } private: char * pData; }; test fun( test Aa){ test Bb(" 0000") ; Bb = Aa ; Bb.set(" 2222"); return Bb ; } int main() { test A(" 1111"); test B = fun( A ) ; test C = A ; A = B; }
运行结果如下:
this is construction of test 1111 //A的构造函数 this is copy construction of test 1111 //传值产生的结果,即A拷贝了一个Aa this is construction of test 0000 //Bb的构造函数 this is operator = : 0000= 1111 //Bb=Aa的结果 this is copy construction of test 2222 //return Bb;用Bb构造了一个B,所以调用的是拷贝构造函数 this is dectruction of test 2222 //Bb的析构函数 this is dectruction of test 1111 //Aa的析构函数 this is copy construction of test 1111 //语句Test C = A 的构造函数,这里没有调用operator=,因为拷贝构造函数效率更高,算是一种优化把 this is operator = : 1111= 2222 //A=B操作的结果 this is dectruction of test 1111 //C的析构函数 this is dectruction of test 2222 //B的析构函数 this is dectruction of test 2222 //A的析构函数 Press any key to continue