C++运算符重载实现的过程
#include <iostream>
using namespace std;
//定义一个复数类
class Complex{
private:
int real;
int vir;
public:
//无参构造
Complex(){}
//有参构造
Complex(int r,int v):real(r),vir(v){}
//展示函数
void show(){
if(vir>=0){
cout<<real<<"+"<<vir<<"i"<<endl;
}
else{
cout<<real<<vir<<"i"<<endl;
}
}
//加法运算符重载
const Complex operator+(const Complex &R)const{
Complex c;
c.real=this->real+R.real;
c.vir=this->vir+R.vir;
return c;
}
//减法运算符重载
const Complex operator-(const Complex &R)const{
Complex c;
c.real=this->real-R.real;
c.vir=this->vir-R.vir;
return c;
}
//关系运算符重载
bool operator>(const Complex &R)const
{
return this->real>R.real&&this->vir>R.vir;
}
bool operator<(const Complex &R)const
{
return this->real<R.real&&this->vir<R.vir;
}
//累加法运算符重载
Complex & operator+=(const Complex &R){
this->real+=R.real;
this->vir+=R.vir;
return *this;
}
//累减法运算符重载
Complex & operator-=(const Complex &R){
this->real-=R.real;
this->vir-=R.vir;
return *this;
}
//前置自增运算符重载
Complex & operator++(){
++this->real;
++this->vir;
return *this;
}
//后置自增运算符重载
Complex operator++(int){
Complex c;
c.real=this->real++;
c.vir=this->vir++;
return c;
}
//中括号运算符重载
int & operator[](int index){
if(0==index){
return real;
}
else if(1==index){
return vir;
}
}
//将全局函数版实现的输出运算符重载函数设置成友元
friend ostream &operator<<(ostream &L, Complex &c);
};
//输出运算符重载
ostream & operator<<(ostream &L,Complex &c){
if(c.vir>=0){
L<<c.real<<"+"<<c.vir<<"i"<<endl;
}
else{
L<<c.real<<c.vir<<"i"<<endl;
}
return L;
}
int main()
{
Complex c(5,3);
c.show();
Complex c1(2,-4);
c1.show();
Complex c2=c+c1;
c2.show();
Complex c3=c-c1;
c3.show();
if(c1 < c2)
{
cout<<"yes"<<endl;
}else
{
cout<<"no"<<endl;
}
c3+=c1;
c3.show();
c3++;
c3.show();
++c;
c.show();
return 0;
}