c++学习-oop-深复制、浅复制

在这里插入图片描述

/*
	Date: 10/03/21 20:45
	Description: 深复制、浅复制
	复制构造函数/拷贝构造函数
	浅复制/浅拷贝/位拷贝
	深复制/深拷贝 
*/
#include<iostream>
#include<cstring>
using namespace std;

class CDemo
{
public:
	CDemo(int pa,char *cstr)
	{
		this->a = pa;
		this->str = new char[1024];
		strcpy(this->str,cstr);
	}
	
							//C++会自动帮我写一个复制构造函数
	CDemo(const CDemo &obj)	//自己写的复制构造函数 
	{
		this->a = obj.a;
//		this->str = obj.str;//这里不对,要深复制才行,这是浅复制
		this->str = new char[1024];
		if(str!=0)
			strcpy(this->str,obj.str);
	}
	
	~CDemo()
	{
		delete str;
	}
public://应该是私有的 
	int a;
	char *str;
};
int main()
{
	CDemo A(10,"hello");
	
	CDemo B = A;//复制 
	
	cout<<A.a<<","<<A.str<<endl;
	cout<<B.a<<","<<B.str<<endl;
	
	B.str[0] = 'o';//Emergency
	
	cout<<A.str<<endl;
	 
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值