|
楼主 |
发表于 2021-4-24 15:01:48
|
显示全部楼层
#include<iostream.h>
#include<string>
#include<stdlib.h>
class Mystring
{
public:
Mystring();
friend istream& operator>>(istream&,Mystring&);
friend ostream& operator<<(ostream&,Mystring&);
Mystring operator+=(Mystring&);
void operator=(Mystring&);
bool operator==(Mystring&);
bool operator!=(Mystring&);
bool operator>(Mystring&);
bool operator<(Mystring&);
~Mystring();
private:
char*pstr;
int length;
};
Mystring::Mystring()
{
pstr=NULL;
cout<<"调用构造函数!"<<endl;
}
istream& operator>>(istream&in,Mystring&a)
{
cout<<"enter length"<<endl;
in>>a.length;
a.pstr=new char[a.length+1];
cout<<"enter pstr"<<endl;
in>>a.pstr;
return in;
}
ostream& operator<<(ostream&out,Mystring&b)
{
out<<b.length<<" ";
out<<b.pstr<<endl;
return out;
}
Mystring Mystring::operator+=(Mystring&a)
{
char* temp = new char[length + a.length + 1];
strcpy(temp,pstr);
strcat(temp,a.pstr);
pstr = temp;
length = length + a.length;
return *this;
}
void Mystring::operator=(Mystring&b)
{
this->length=b.length;
this->pstr=new char[length+1];
strcpy(this->pstr,b.pstr);
}
bool Mystring::operator==(Mystring&a)
{
if(length==a.length&&strcmp(pstr,a.pstr)==0)
return true;
else
return false;
}
bool Mystring::operator!=(Mystring&a)
{
if(this->length!=a.length||strcmp(this->pstr,a.pstr)!=0)
return true;
else
return false;
}
bool Mystring:: operator>(Mystring&a)
{
if(strcmp(pstr,a.pstr)>0&&this->length>a.length)
return true;
else
return false;
}
bool Mystring::operator<(Mystring&a)
{
if(strcmp(pstr,a.pstr)<0&&this->length<a.length)
return true;
else
return false;
}
Mystring::~Mystring()
{
//delete[]pstr;
cout<<" Mystring 调用析构函数!"<<endl;
}
int main()
{
Mystring a,b,c,d;
cin>>a>>b;
cout<<"a:"<<a<<endl;
cout<<"b:"<<b<<endl;
c=a;
cout<<"c:"<<c<<endl;
d=b+=c;
cout<<"d:"<<d<<endl;
if(a<d) cout<<"a<d yes"<<endl;
else cout<<"a<d no"<<endl;
if(a>b) cout<<"a>b yse"<<endl;
else cout<<"a>b no"<<endl;
if(a==c) cout<<"a==c yse"<<endl;
else cout<<"a==c no"<<endl;
if(b!=c) cout<<"b!=c yes"<<endl;
else cout<<"b!=c no"<<endl;
return 0;
}大佬 后面我改成了这个样子 基本可以运行了,, |
|