深入理解各种构造函数

#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

俗话说得好,好记性不如烂笔头啊,自己写得代码,现在居然看不懂了……

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值