运算符之深度复制拷贝

#include"aa.h"
#include<iostream.h>
#include<stdio.h>
#include<string.h>


class bb
{
public:
char *i;
bb ()
{this->i=0;
printf("no pram!\n");
}


bb (char *i)//深度复制
{this->i=new char[10];
strcpy(this->i,i);
printf("with pram!\n");
}
~bb()//析构函数
{
if(0!=this->i)
delete this->i;
printf("destry!\n");
}




};






int main()
{
bb a;
a="tom";




return 0;
}




#include"aa.h"
#include<iostream.h>
#include<stdio.h>
#include<string.h>


class bb
{
public:
char *i;
bb ()
{this->i=0;
printf("no pram!\n");
}


bb (char *i)//深度复制
{this->i=new char[10];
strcpy(this->i,i);
printf("with pram!\n");
}
~bb()//析构函数
{
if(0!=this->i)
delete this->i;
printf("destry!\n");
}




};






int main()
{
bb a("tom");
bb a1=a;//属于浅度复制






return 0;
}


以上这里就会出错,2次运行析构函数,对同一个地方2次销毁,所以就会出错,则用赋值运算符重载来进行复制。
加上这个就不会出错啦
bb & operator=(bb &b)
{
this->i=new char[10];
strcpy(this->i,b.i);
return *this;
}
对于这样,要拷贝构造函数
bb (bb &b)//一定要&,不然会进入死循环
{this->i=new char[10];
strcpy(this->i,b.i);
printf("深度复制!\n");
}


总的为
#include"aa.h"
#include<iostream.h>
#include<stdio.h>
#include<string.h>


class bb
{
public:
char *i;

bb ()
{this->i=0;
printf("no pram!\n");
}
bb (bb &b)//
{this->i=new char[10];
strcpy(this->i,b.i);
printf("深度复制!\n");
}


bb (char *i)//深度复制
{this->i=new char[10];
strcpy(this->i,i);
printf("with pram!\n");
}
~bb()//析构函数
{
if(0!=this->i)
delete this->i;
printf("destry!\n");
}
bb & operator=(bb &b)
{
this->i=new char[10];
strcpy(this->i,b.i);
return *this;
}


};






int main()
{


bb a("tom"),a1;
 a1=a;
 bb a2=a1;






return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值