C++深拷贝和浅拷贝

浅拷贝只复制了对象的指针,对象指针指向的数据还是同一块内存空间,析构函数只能调用一次
深拷贝不仅复制了对象指针,对象指针指向的数据也在堆区重新申请内存空间,进行拷贝操作 ,析构操作正常进行

#include<iostream>
#include<cstring>
using namespace std;
class A
{
	public:
	A();
	A(const char* ,int );
	A(const A&);//浅拷贝构造函数是没有这个拷贝构造函数
	//调用的是系统默认的拷贝构造函数 
	~A();
	void show();
	//浅拷贝只复制了对象的指针,对象指针指向的数据还是同一块内存空间,析构函数只能调用一次
	//深拷贝不仅复制了对象指针,对象指针指向的数据也在堆区重新申请内存空间,进行拷贝操作 ,析构操作正常进行 
	private:
		char* name;
		int score;
		static int g; //计算调用几次构造函数
		static int x;//计算调用几次析构函数
};

int A::g = 0;
int A::x = 0;

A::A(){
	cout<<"默认无参构造函数"<<endl; 
}

A::A(const char* Name,int p){
	name=new char[strlen(Name)+1];
	strcpy(name,Name);
	score=p;
	cout<<"初始化构造函数"<<endl; 
}	
	
A::A(const A& a){	
	name=new char[strlen(a.name)+1];
	strcpy(name,a.name);
	score=a.score;
	g++;
	cout << "第" << g << "次调用:";
	cout<<"深拷贝构造函数"<<endl;
}

A::~A(){
	x += 1;
	cout << "第" << x << "次调用:";
	cout << "析构函数"<<name<< endl;
	delete[] name;
	name=NULL;
}

void A::show(){
	cout<<"Name: "<<name<<"\t"<<"Score: "<<score<<endl;
}

void test01(){
	string name="abcdefg";
	A a1(name.c_str(),100);
	a1.show();
	A a2=a1;
	a2.show();
}

int main(){
	test01();
	return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SODA_BLUEBLUE

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值