运算符之深度复制拷贝

来源:互联网 发布:梓潼淘宝运营招聘 编辑:程序博客网 时间:2024/05/22 01:27
#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;
}

0 0
原创粉丝点击