这里好像有两个错误,一个是内存泄漏,还有一个是size,以后复习再改
#include<iostream>
#include<cstring>
using namespace std;
class Mystring{
public:
Mystring(const char *a =""); //构造函数
Mystring(const Mystring &other); //复制构造
Mystring & operator =(const Mystring &fir); //复制赋值
Mystring (Mystring &&other); //移动构造
Mystring & operator=(Mystring && other); // 移动赋值
Mystring operator + (const Mystring &fir); //+字符串连接
Mystring TakeString(int i,int j); //取子串函数,当前对象是母串
char& operator[](int i); //重载下标运算符
~Mystring(); //析构函数
friend istream &operator>>(istream &in,Mystring &other);//输入
friend ostream & operator<<(ostream &out, Mystring &other);//输出
private:
int Long;//计长度
char *A;//字符串
};
Mystring::Mystring(const char *a) // 构造函数
{
if (a == nullptr)
a = ""; // 将空指针转化为空串
A = new char[strlen(a) + 1];// 分配存储空间
Long=strlen(a);
strcpy(A, a); // 复制串值
}
Mystring::Mystring(const Mystring &other)//复制构造函数
{
A=new char[other.Long+1];
Long=other.Long;
strcpy(A,other.A);
}
Mystring& Mystring::operator =(const Mystring &fir)//复制赋值
{
if(this==&fir)
{
return *this;
}
else
{
delete []A;//避免内存泄漏,先释放原先申请的
A=new char[fir.Long+1];
strcpy(A,fir.A);
Long=fir.Long;
return *this;
}
}
Mystring &Mystring:: operator=(Mystring && other)// 移动赋值
{
char *t;//交换字符串
t=A;
A=other.A;
other.A=t;
int l;//交换长度
l=Long;
Long=other.Long;
other.Long=l;
return *this;
}
Mystring:: Mystring(Mystring &&other)//移动构造
{
A = other.A;
Long=other.Long;
other.A = nullptr;
}
Mystring Mystring::operator+(const Mystring &fir)//连接函数
{
Mystring newString;
delete [] newString.A;
newString.A=new char[this->Long+fir.Long+1];//接着再申请一个要加入的字符串的长度
newString.Long=this->Long+fir.Long;
strcpy(newString.A,this->A);
strcat(newString.A,fir.A);
return newString;
}
Mystring Mystring::TakeString(int i,int j)//取子串函数,当前对象是母串
{
Mystring result;
delete []result.A;
result.Long=j;
result.A=new char[result.Long+1];
strncpy(result.A,A+i,j);
return result;
}
char& Mystring::operator[](int i)
{
if( i > Long )
{
cout<<"查询不到"<<endl;
}
return *(A+i);
}
ostream& operator<<(ostream &out, Mystring &other)
{
out<<other.A;
return out;
}
istream &operator>>(istream &in,Mystring &other)
{
char t[200];
in>>t;
other.Long=strlen(t);
other.A=new char[other.Long+1];
strcpy(other.A,t);
return in;
}
Mystring::~Mystring()//好像这里的处理不是很好
{
//cout<<"xigou"<<endl;
if(A!=nullptr)
{
delete []A;
A=nullptr;
}
}
int main()
{
/*Mystring first(" best it");
cout<<first[3]<<endl;下标运算符重载的测试
Mystring a("ok");
Mystring b,c;
c=a+b;
cout<<a<<b<<c;*/
Mystring S[4];
char p;
int i,j,k,l;
cin>>S[0]>>S[1];
while(cin>>p)
{
switch(p)
{
case 'P':
cin>>i;
cout<<S[i-1]<<endl;
break;
case 'A':
cin>>i>>j;
S[j-1]=S[i-1];
break;
case 'C':
cin>>i>>j>>k;
S[k-1]=S[i-1]+S[j-1];
break;
case 'F':
cin>>i>>j>>k>>l;
S[l-1]=S[i-1].TakeString(j,k);
break;
}
}
return 0;
}