#include<iostream>
#include<cstring>
using namespace std;
class Parent{
private:
char *a;
int len;
public:
Parent(){
a = nullptr;
len = 0;
}
Parent(const char *n){
if(nullptr != n){
len = strlen(n);
a = new char(len+1);
strcpy(a,n);
}
else{
a = nullptr;
len = 0;
}
}
~Parent(){
delete []a;
a = nullptr;
}
Parent(const Parent& other){
len = other.len;
a = new char[len+1];
strcpy(a,other.a);
}
Parent& operator=(const Parent& other){
if(&other != this){
len = other.len;
if(a == nullptr)
a = new char[len+1];
strcpy(a,other.a);
}
return *this;
}
const Parent operator+(Parent &R) const{
Parent x;
if(a!=nullptr&&R.a!=nullptr){
x.len=len+R.len;
x.a=new char[len+1];
strcpy(x.a,a);
strcat(x.a,R.a);
return x;
}
else
{
cout << "空字符串无法拼接" << endl;
return x;
}
}
const bool operator!=(Parent &R)const{
if((a!=nullptr)&&(R.a!=nullptr)){
if(strcmp(a,R.a)==0)
return 0;
else
return 1;
}
else{
cout << "字符串不存在" << endl;
return 0;
}
}
const bool operator==(Parent &R)const{
if(strcmp(a,R.a)==0)
return 1;
return 0;
}
const bool operator<(Parent &R)const{
int x=strcmp(a,R.a);
if(x<0)
return 1;
else
return 0;
}
const bool operator<=(Parent &R)const{
int x=strcmp(a,R.a);
if(x<0||x==0)
return 1;
return 0;
}
const bool operator>(Parent &R)const{
int x=strcmp(a,R.a);
if(x>0)
return 1;
return 0;
}
const bool operator>=(Parent &R)const{
int x=strcmp(a,R.a);
if(x>0||x==0)
return 1;
return 0;
}
const int size()const{
return strlen(a);
}
const char *res(){
if(a!=nullptr)
{
char *s=nullptr;
s=a;
return s;
}
else{
cout << "空字符串无法展示" << endl;
return nullptr;
}
}
friend ostream& operator<<(ostream& L,const Parent& R);
friend istream& operator>>(istream& L, Parent& R);
};
ostream& operator<<(ostream& L, const Parent& R){
L <<"字符串="<< R.a <<"长度=" << R.size() <<endl;
return L;
}
istream& operator>>(istream& L, Parent& R){
cout<<"请输入\n";
L >>R.a;
return L;
}
int main(){
Parent s1("hello");
Parent s2("word");
Parent s3;
s3=s1+s2;
cout << "s3=" << s3.res() << endl;
bool ret=s1!=s2;
cout << "s1!=s2 " << ret << endl;
ret=s1==s2;
cout << "s1==s2 " << ret << endl;
ret=s1<s2;
cout << "s1<s2 " << ret << endl;
ret=s1<=s2;
cout << "s1<=s2 " << ret << endl;
ret=s1>s2;
cout << "s1>s2 " << ret << endl;
ret=s1>=s2;
cout << "s1>=s2 " << ret << endl;
cin>>s3;
cout <<s3;
return 0;
}
作业,实现运算符的重写
最新推荐文章于 2024-10-16 22:52:46 发布