C++构造函数 拷贝赋值

class MyString
{
public:
MyString();
MyString(int newsize);
MyString(const MyString& ms);
const MyString& operator=(const MyString& ms);
virtual ~MyString();
private:
int *ptr;
int size;

};
/
MyString::MyString(int newsize)
{

size = newsize;
ptr = new int[size];
for(int i=0; i < size; i++){
ptr[i] = 0;
}
cout<<"construct is executing size is "<<size<<endl;

}
MyString::MyString(const MyString& ms){

size = ms.size;
ptr = new int[size];
for(int i = 0; i < size ; i++){
ptr[i] = ms.ptr[i];
}
cout<<"copy construct is executing.."<<"address of ptr is "<<ptr<<endl;
}
const MyString& MyString::operator=(const MyString& ms){
cout<<"operator is executing"<<endl;
if(this != &ms){
delete[] ptr;
size = ms.size;

ptr = new int[size];
for(int i = 0; i < size ; i++){
ptr[i] = ms.ptr[i];
}
return *this;
}
}

MyString::~MyString()
{
cout<<"desturct address of ptr is "<<ptr<<endl;
delete[] ptr;

}

MyString play(MyString a)
{
return a;
}
int main(int argc, char* argv[])
{
//printf("Hello World!\n");
/*testint t1 = play(4);
testint t2 = play(5);
testint t3 = play(t1);*/
MyString ms1 = MyString(5);
MyString ms2 = play(ms1);

return 0;
}

输出结果:

[img]/upload/attachment/105992/ff084db7-b188-3bba-8151-3b1a9d8fca3c.bmp[/img]
注意将play(ms1)的返回值赋值给ms2,执行拷贝函数。然后返回值再析构
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值