国庆作业 day 4

 C++运算符重载代码实现的过程

#include 
 
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-R.real;
        c.vir=this->vir-R.vir;
        return c;
    }
    //重载:+=  实部+=实部 虚部+=虚部
    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;
    }
     //重载中括号[]运算符
    int & operator[](int index)
    {
        if(index==0)
        {
            return real;
        }
        else if(index==1)
        {
            return vir;
        }
    }
 
 
    //重载前置自增运算符重载函数:实部 = 实部+1   虚部=虚部+1
    Complex &operator++()
    {
        ++this->real;
        ++this->vir;
 
        return *this;
    }
    //重载后置自增运算符重载函数:实部 = 实部+1   虚部=虚部+1
    Complex operator++(int)
    {
        Complex c;
 
        c.real = this->real++;
        c.vir = this->vir++;
 
        return c;
    }
 
};
int main()
{
    Complex c1(5,3);
    Complex c2(2,1);
    c1.show();    //测试
 
    Complex c3=c1-c2;
    c3.show();
 
    Complex c4=c1+=c2;   //测试+=
    c4.show();
 
    Complex c5=c1-=c2;
    c5.show();
 
    c5[0]=10;        //将实部参数进行修改
    c5.show();
 
    Complex c6=++c1;   //测试自增
    c6.show();
    Complex c7=c2++;;
    c7.show();
    return 0;
}

你可能感兴趣的:(c++,算法,开发语言)