国庆10.3

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;
    }

    //成员函数版实现关系运算符的重载:实部>实部 虚部>虚部
    bool operator> (const Complex &R)const
    {
        return this->real>R.real&&this->vir>R.vir;
    }

    //重载中括号运算符
    int & operator[](int index)
    {
        if(index == 0)
        {
            return real;        //返回实部
        }else if(index == 1)
        {
            return vir;         //返回虚部
        }
    }

    //重载 +=运算符:实部+=实部 虚部+=虚部
    Complex &operator+=(const Complex &R)
    {
        this->real += R.real;
        this->vir += R.vir;

        return  *this;              //返回自身的引用
    }

    //重载负号运算符:实部= -实部,虚部= -虚部
    Complex operator-()
    {
        Complex c;
        c.real = this->real;
        c.vir = this->vir;

        return c;
    }

    //重载前置自增运算符重载函数:实部=实部+1 虚部=虚部+1
    Complex &operator++()
    {
        ++this->real;   //等同于this->real++
        ++this->vir;

        return *this;    //先加一再使用
    }

    //重载后置自增运算符重载函数:实部=实部+1 虚部=虚部+1
    Complex operator++(int)
    {
        Complex c;
        c.real = this->real++;
        c.vir = this->vir++;

        return  c;
    }

    //将全局版的重载输出运算符函数设置成友元
    friend ostream &operator<<(ostream &L, Complex &c);

    //重载小括号运算符,做一个仿函数
    void operator()(string s)
    {
        cout<= 0)
    {
        L< c2)             //调用关系运算符重载函数
    {
        cout<<"yes"<

你可能感兴趣的:(作业,c++)