C++ : String类

本文深入解析C++中拷贝构造函数的作用与实现,包括如何利用已有的对象生成新对象,复制对象作为实参传给函数,从函数返回时复制对象,以及初始化顺序容器中的元素等场景。同时,探讨了当拷贝构造函数形参非引用类型时可能引发的递归调用问题。

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

class String
{
public:
	String(const char *str = NULL);
	~String();
	String(const String &other);
	String &operator = (const String &other);
private:
	char *data;
};

String::String(const char *str)
{
	if(NULL == str)
	{
		data = new char[1];
		*data = '\0';
	}
	else
	{
		int len = strlen(str);
		data = new char[len+1];
		strcpy(data,str);
	}
}

String::~String()
{
	delete []data;
}

String::String(const String&other)
{
	int len = strlen(other.data);
	data = new char[len+1];
	strcpy(data,other.data);
}

String &String::operator = (const String &other)
{
	if(this == &other)
	{
		return *this;
	}
	delete []data;

	int len = strlen(other.data);
	data = new char[len+1];
	strcpy(data,other.data);
	return *this;
}

拷贝构造函数的作用:

a.利用已有的对象显示或者隐式生成一个新对象

b.复制一个对象,将它作为实参传给一个函数

c.从函数返回时复制一个对象

d.初始化顺序容器中的元素

e.显示初始化(利用数组的初始化列表)数组元素

 

对象间的赋值会调用拷贝构造函数,如果拷贝构造函数的形参不是对象的引用而是对象本身调用时会发生什么?

String(const String other)是值传递主调函数[ String t2(t1) ]会把实参的副本传递给形参,那么实参的副本是怎么来的呢?当然还是调用拷贝构造函数生成的,但是调用拷贝构造函数生成副本的过程中,又会调用拷贝构造函数,这样,拷贝构造函数会一直递归调用,直到消耗尽栈空间,最后程序崩溃。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值