继续完成my_string 类的书写,主要完成运算符重载:
+=运算符:operator+=
下标运算符:operator[]
加法运算符:operator+
关系运算符:> 、 <、==
要求:自己分析函数,该加const的要准确加上
#include <iostream>
using namespace std;
class my_string
{
private:
int rea;//实部
int vir;//虚部
char *str;
public:
my_string(){}
my_string(int r,int v):rea(r),vir(v){}
void show()
{
cout<<rea<<"+"<<vir<<"i"<<endl;
}
//实现+运算符重载:实部+实部 虚部+虚部
const my_string operator+(const my_string& R)const
{
my_string temp;
temp.rea=this->rea+R.rea;
temp.vir=this->vir+R.vir;
return temp;
}
friend const my_string operator-(const my_string& L,const my_string& R);
//实现+=运算符重载
my_string & operator+=(const my_string R)
{
this->rea+=R.rea;
this->vir+=R.vir;
return *this;
}
friend my_string & operator-=(my_string &L,const my_string &R);
//实现>运算符重载
bool operator>(const my_string R)
{
return this->rea>R.rea&&this->vir>R.vir;
}
//实现<运算符重载
bool operator<(const my_string R)
{
return this->rea<R.rea&&this->vir<R.vir;
}
//实现==运算符重载
bool operator==(const my_string R)
{
return this->rea==R.rea&&this->vir==R.vir;
}
//实现-(负号)运算符重载
const my_string operator-()const
{
my_string temp;
temp.rea=-this->rea;
temp.vir=-this->vir;
return temp;
}
//实现后置++
my_string operator++(int)
{
my_string temp;
temp.rea=this->rea++;
temp.vir=this->vir++;
return temp;
}
//实现下标
char operator[](const int n)
{
char temp;
temp=this->str[n];
return temp;
}
};
//负号
const my_string operator-(const my_string& L,const my_string& R)
{
my_string temp;
temp.rea=L.rea-R.rea;
temp.vir=L.vir-R.vir;
return temp;
}
my_string & operator-=(my_string &L,const my_string &R)
{
L.rea-=R.rea;
L.vir-=R.vir;
return L;
}
int main()
{
my_string c1(3,6);
c1.show();
my_string c2(6,7);
c2.show();
my_string c3;
c3+=c1;
c3.show();
my_string c4(6,8);
c4=c1+c2;
c4.show();
if(c1>c2)
{
cout<<"yes"<<endl;
}
else
{
cout<<"no"<<endl;
}
if(c1==c2)
{
cout<<"yes"<<endl;
}
else
{
cout<<"no"<<endl;
}
if(c1<c2)
{
cout<<"yes"<<endl;
}
else
{
cout<<"no"<<endl;
}
return 0;
}