在myString基础上,将能够重载的运算符全部进行重载
#include <iostream>
#include<cstring>
using namespace std;
class mystring;
class mystring
{
char *str;
int size;
int a,b;
public:
mystring(int A,int B):a(A),b(B){}
void A_show()
{
if(b>0)
{
cout<<a<<"+"<<b<<endl;
}
else
{
cout<<a<<""<<b<<endl;
}
}
mystring():size(10)//无参构造
{
str=new char[size];
strcpy(str,"");
}
mystring(const char *s)//有参构造
{
size=strlen(s);
str=new char[size+1];
strcpy(str,s);
}
//拷贝构造
mystring(const mystring &other):str(other.str),size(other.size)
{
str=new char[other.size];
strcpy(str,other.str);
cout<<""<<str<<endl;
}
//析构函数
~mystring()
{
delete str;
cout<<"mystring::析构函数,this="<<this<<endl;
}
//判空函数
bool empty()
{
if(sizeof(str)==0)
{
cout<<"空"<<endl;
return 0;
}
return 0;
}
//size函数
int mystring_size()
{
cout<<""<<size<<endl;
return size;
}
//c_str函数
string c_str()
{
return this->str;
}
//at函数
char &at(int pos)
{
if(pos<0||pos>=size)
{
cout<<"错误"<<endl;
}
char &a=str[pos];
return a;
}
int &operator[](int pos)
{
if(pos==1)
{
return this->a;
}
else if(pos==2)
{
return this->b;
}
else
{
cout<<"越界"<<endl;
}
return this->a;
}
mystring &operator=(const mystring &R)
{
this->a=R.a;
this->b=R.b;
return *this;
}
const mystring operator+(const mystring &R)const
{
mystring temp;
temp.a=this->a+R.a;
temp.b=this->b+R.b;
return temp;
}
bool operator==(const mystring &R)const
{
return this->a==R.a&&this->b==R.b;
}
bool operator!=(const mystring &R)const
{
return this->a!=R.a&&this->b!=R.b;
}
bool operator<(const mystring &R)const
{
return this->a<R.a&&this->b<R.b;
}
bool operator>(const mystring &R)const
{
return this->a>R.a&&this->b>R.b;
}
bool operator<=(const mystring &R)const
{
return this->a<=R.a&&this->b<=R.b;
}
bool operator>=(const mystring &R)const
{
return this->a>=R.a&&this->b>=R.b;
}
friend ostream &operator<<(ostream &L,const mystring &R);
friend istream &operator>>(istream &L,mystring &R);
};
ostream &operator<<(ostream &L,const mystring &R)
{
if(R.b>0)
{
L<<R.a<<"+"<<R.b<<endl;
}
else
{
L<<R.a<<"-"<<R.b<<endl;
}
return L;
}
istream &operator>>(istream &L,mystring &R)
{
L>>R.a;
L>>R.b;
return L;
}
int main()
{
/* mystring s1("hello");
mystring s2(s1);
s2.mystring_size();
cout<<""<<s2.at(1)<<endl;*/
mystring c1(3,5);
cout<<c1;
mystring c2(4,-2);
c2.A_show();
mystring c3;
c3=c1+c2;
return 0;
}