C++浅层与深层复制构造函数

//层复制构造函数代码

#include<iostream>
using namespace std;
class Test 
{
public:
	Test()
	{
		x=new int;
		*x=100;
	}
	~Test()
	{
		delete x;
		x=NULL;
		cout<<"析构函数正在执行......"<<endl;
	}
	Test(const Test & t)//这个是浅层复制构造,系统默认会提供,这里写出来便于分析
	{
		x=t.x;
	}
	void Display()
	{
		cout<<"x的值是:"<<*x<<endl;
	}
	void SetValue(int val)
	{
		*x=val;
	}
private:
	int *x;
};
int main()
{
	Test *T=new Test;
	Test t=*T;
	T->Display();
	t.Display();
	
	t.SetValue(1);

	cout<<"重新设置值后:"<<endl;
	T->Display();
	t.Display();
	return 0;
}

执行结果:

 

 

深层复制构造函数代码

 

#include<iostream>
using namespace std;
class Test 
{
public:
	Test()
	{
		x=new int;
		*x=100;
	}
	~Test()
	{
		delete x;
		x=NULL;
		cout<<"析构函数正在执行......"<<endl;
	}
	Test(const Test & t)
	{
		x=new int;  //为x分配地址空间
		*x=*(t.x);  //赋值
	}
	void Display()
	{
		cout<<"The value of x:"<<*x<<endl;
	}
	void SetValue(int val)
	{
		*x=val;
	}
private:
	int *x;
};
int main()
{
	Test *T = new Test;
	Test t = *T;  
	//Test t;  t=*T 这两条语句不能代替上面Test t = *T;
	//因为上面那条语句是初始化,而下面这条语句是赋值,初始化才调用复制构造函数
	
	T->Display();
	t.Display();

	t.SetValue(1);

	cout<<"重新设置值后:"<<endl;
	T->Display();
	t.Display();
	delete T;
	return 0;
}


执行结果:



 

复制构造函数调用的条件有以下几个:

1用类的一个对象初始化该类的另一个对象时
2
如果函数的形参是类的对象,调用函数时,进行形参和实参结合时. 
3
如果函数的返回值是类的对象,函数执行完成返回调用者时.
4
需要产生一个临时类对象时。

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值