标准重载代码

来源:互联网 发布:java 线程局部变量 编辑:程序博客网 时间:2024/06/07 22:33
#include "iostream"using namespace std;class  Complex{private:    int a;    int b;    friend ostream& operator<<(ostream &out, Complex &c1);public:    Complex(int a = 0, int b = 0)    {        this->a = a;        this->b = b;    }    void printCom()    {        cout<<a<<"+"<<b<<"i"<<endl;    }public:    //通过类的成员函数实现-操作    Complex operator-(Complex &c2)    {        Complex tmp;        tmp.a = this->a -c2.a;        tmp.b = b -c2.b;        return tmp;    }    Complex operator+(Complex &c2)    {        Complex tmp;        tmp.a = this->a + c2.a;        tmp.b = b + c2.b;        return tmp;    }    // 前置--    Complex& operator--()    {        this->a--;        this->b--;        return *this;    }    // 前置++    Complex& operator++()    {        this->a++;        this->b++;        return *this;    }    //后置--    Complex operator--(int)    {        Complex tmp = *this;        this->a --;        this->b --;        return tmp;    }    //后置++    Complex operator++(int)    {        Complex tmp = *this;        this->a ++;        this->b ++;        return tmp;    }};//1操作符重载,首先是通过函数实现的。int main(){    Complex c1(1, 2), c2(3, 4);    Complex c3 = c1 + c2;    c3.printCom();    Complex c5 = c1 - c2 ;    c5.printCom();    ++c2;    c2.printCom();    --c2;    c2.printCom();    c2++;    c2.printCom();    c2--;    c2.printCom();    return 0;}
0 0
原创粉丝点击