C++拷贝构造函数的调用时机,如没有重载等号操作符,需重写使用深拷贝

本文详细阐述了C++中拷贝构造函数的调用时机及其在不同场景下的应用,通过实例展示了如何正确重载拷贝构造函数以实现深复制,并讨论了拷贝构造函数在类实例化过程中的作用。

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

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
/**拷贝构造函数 调用时机:(以下会调用copy)
Test t1;
Test t2=t1;//如果没有重载=操作符,
Test t1(t2);
void function(t1);//t1实参初始化形参 ,形参是一个元素 
Test function(){
//函数的返回值是一个元素时 返回的是一个匿名对象
return t1;
}


*/
class Test {
public:
	Test() {
		a = 10;
		p = (char*)malloc(sizeof(char)*100);
		strcpy(p,"helloword!");
		cout << "start" << endl;
	}
	void print() {
		cout << a << endl;
		cout << p << endl;
	
	}
	Test(const Test& ogj){//复写copy构造函数 使用深copy
		this->p = (char*)malloc(100);
		strcpy(this->p,ogj.p);
		this->a = ogj.a;
		cout << "copy" << endl;
	}
	Test(int a,char *p) {
		this->a = a;
		this->p = (char*)malloc(sizeof(char) * 100);
		strcpy(this->p, p);
	}


	~Test() {
		if(p!=NULL){
			free(p);
		}
		cout << "end" << endl;
		}
private :
	int a;
	char *p;


};


void function() {
	
	char* a = "hello";
	Test t3(12,a);
	
	Test t4 = t3;
	t4.print();
}


void main() {


	function();


	system("pause");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值