#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;
}
OOP CString字符串拼接(深拷贝与运算符重载)
于 2023-05-10 22:11:09 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)