C++ 中的赋值运算符重载和复制构造函数

本文通过一个具体的C++类实现示例,深入探讨了浅复制与深复制的区别及其应用场景。通过对复制构造函数和赋值操作符重载的定义与使用,展示了如何正确管理动态分配的资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


浅复制:

 


深复制

 


/*
**	在C++中,存在浅复制和深复制,浅复制仅仅将内部数据的值拷贝一份
*/ 

#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;

class Demo
{
private:
	char *buffer;
public:
	Demo(const char *str);
 	Demo(const Demo & copy);
	~Demo();
	Demo & operator=(const Demo & CopyDemo);
	void print(void);
};

Demo::Demo(const char *str)
{
	if (str!=NULL)
	{
		buffer = new char [strlen(str)+1];
		strcpy(buffer,str);
	}
	else
		buffer = NULL;
}

Demo::Demo(const Demo & copy)
{
	if (copy.buffer != NULL)
	{
		buffer = new char [strlen(copy.buffer)+1];
		strcpy(buffer,copy.buffer);
		cout<<"Copy Call"<<endl;
	}
	else
		buffer = NULL;
}


Demo::~Demo()
{
	if (buffer!=NULL)
	{
		delete [] buffer;
		cout<<"Delete Call"<<endl;
	}
}

void Demo::print()
{
	cout<<buffer<<endl;
}

/*	重载赋值符号,下面左边的 & 不能漏,否则不影响原来的值	*/ 
Demo & Demo::operator=(const Demo & CopyDemo)
{
	if (CopyDemo.buffer!=NULL)
	{
		buffer = new char [strlen(CopyDemo.buffer)+1];
		strcpy(buffer,CopyDemo.buffer);
		cout<<"Operator = Call"<<endl;
	}
	else
		buffer = NULL;
} 

void Copy(Demo CopyDemo)
{
	CopyDemo.print();
	cout<<"Call"<<endl;
}

int main()
{
	Demo demo("Hello");
	Copy(demo);		//调用赋值构造函数进行深度复制 
	demo.print();
	
	
	cout<<endl;
	Demo t("H");
	temp = demo;	//由于t存在,所以调用赋值运算符重载函数 
	temp.print();
	
	
	cout<<endl;
	Demo temp = demo;	//由于temp不存在,所以调用复制构造函数 
	
	return 0;
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值