OOP CString字符串拼接(深拷贝与运算符重载)

该代码定义了一个名为CString的类,用于处理字符串。类中包含了构造函数、拷贝构造函数、重载的+、<<和=运算符,以及一个用于拼接字符串的方法。在主函数中,读取用户输入,创建CString对象并进行字符串操作。
摘要由CSDN通过智能技术生成
#include<iostream>
#include<cstring>
using namespace std;

class CString
{
	char* s;
	int n;
public:
	CString(char* const _s=NULL):s(NULL),n(0)        //构造函数 
	{
		if (!_s) return;
		n=strlen(_s);
		s=new char[n + 1]{};
		strncpy(s,_s,n);
	}
	CString(const CString &p)        //拷贝构造函数 
	{
		if(this!=&p)
		{
			s=new char[n+1];
			strcpy(s,p.s);
		}
	}
	friend CString operator+(const CString &p1,const CString &p2)        //重载"+"运算符
	{
		char *temp=new char[p1.n+p2.n+1];
		strncpy(temp,p1.s,p1.n);
        strncpy(temp+p1.n,p2.s,p2.n);
        temp[p1.n+p2.n]='\0';
		CString c(temp);
		return c;
	}
	friend ostream &operator<<(ostream &o,const CString &p)        //重载"<<"运算符
	{
		for(int i=0;i<p.n;i++)
	  		o << p.s[i];
		return o;
	}
	CString operator=(const CString &p)        //重载"="运算符
	{
		if(n!=0)
		    delete s;
		n=p.n;
		s=new char[n+1];
		strcpy(s,p.s);
		return *this;
	}
};

int main()
{
	int n;
	char input[64 + 1]{};
	cin >> n;
	while(n--)
	{
		cin >> input;
		CString s1(input);
		cin >> input;
		CString s2(input);
		CString sEmpty;
		delete new CString(s1=s1+s2);
		cout << s1+sEmpty << endl
			 << sEmpty+s2 << endl
			 << s1+s2 << endl
			 << endl;
	}
	return 0;
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值