【C++】String类拷贝构造函数——深拷贝普通版和简洁版

本文展示了一个简单的C++字符串类的实现,包括构造函数、拷贝构造函数、赋值运算符重载及析构函数等关键成员函数。通过具体实例演示了如何使用该类创建、复制字符串对象以及进行字符串赋值操作。

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

#define  _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;

class String
{
public:
	//构造函数
	String(char* pStr = "")
	{
		if (NULL == pStr)
		{
			_pStr = new char[1];
			*_pStr = '\0';
		}
		else
		{
			_pStr = new char[strlen(pStr) + 1];
			strcpy(_pStr, pStr);
		}
	}

	////拷贝构造函数1 简洁版
	//String(const String& pStr)
	//	:_pStr(NULL)
	//{
	//	String temp(pStr._pStr);
	//	swap(_pStr, temp._pStr);
	//}

	//拷贝构造函数2 普通版

	String(String& pStr)
		:_pStr(new char[strlen(pStr._pStr)+1])
	{
		strcpy(_pStr, pStr._pStr);
	}

	////赋值运算符重载1
	//String& operator=(const String& pStr)
	//{
	//	if (this != &pStr)
	//	{
	//		String temp(pStr._pStr);
	//		swap(_pStr, temp._pStr);
	//	}
	//	return *this;
	//}

	//赋值运算符重载2
	String& operator=(const String& pStr)
	{
		if (this != &pStr)
		{
			//防止new开辟内存失败,丢失原来内存
			char* ptr = new char[strlen(pStr._pStr) + 1];
			strcpy(ptr, pStr._pStr);
			delete[]_pStr;
			_pStr = ptr;
		}
		return *this;
	}


	//析构函数
	~String()
	{
		if (NULL != this)
		{
			delete[]_pStr;
			_pStr = NULL;
		}
	}

	friend ostream& operator<<(ostream& _cout, const String& pStr);
private:
	char* _pStr;
};


ostream& operator<<(ostream& _cout, const String& pStr)
{
	_cout << pStr._pStr;
	return _cout;
}

void Funtest()
{
	String s1("hehe");
	cout << s1 << endl;
	String s2;
	s2 = s1;
	cout << s2 << endl;

	String s3(s1);
	cout << s3 << endl;

}
void Funtest2()
{
	String s1("hello");
	String s2(s1);
	cout << s1 << endl;
	cout << s2 << endl;
	cout << "##################" << endl;

	String s3("world");
	cout << s3 << endl;
	s3 = s1;
	cout << s3 << endl;
	cout << "##################" << endl;
}

int main()
{
	Funtest2();
	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值