C++运算符重载

文章讨论了在C++中如何使用友元函数和成员函数来重载运算符,包括+,-,*,/以及前置和后置的++,--等。对于输入输出运算符<<和>>,文章建议以友元函数方式重载,因为成员函数形式会导致使用时的第一个参数为类对象,不符合常规用法。
摘要由CSDN通过智能技术生成

 以友元函数的方式重载

class Complex
{
private:
    double real, imag;

public:
    Complex() = default;
    Complex(double r, double i);
    ~Complex() = default;

    /* 赋值运算符只能以成员函数的形式重载 */
    Complex& operator=(const Complex &p);

    friend Complex operator+(const Complex &p1, const Complex &p2);
    friend Complex operator-(const Complex &p1, const Complex &p2);
    friend Complex operator*(const Complex &p1, const Complex &p2);
    friend Complex operator/(const Complex &p1, const Complex &p2);
   
    friend Complex operator++(Complex &p, int); // 后置++重载
    friend Complex operator--(Complex &p, int); // 后置--重载
    friend Complex &operator++(Complex &p);     // 前置++重载
    friend Complex &operator--(Complex &p);     // 前置--重载
    
    friend bool operator>(const Complex& p1, const Complex& p2);
    friend bool operator<(const Complex& p1, const Complex& p2);
    friend bool operator>=(const Complex& p1, const Complex& p2);
    friend bool operator<=(const Complex& p1, const Complex& p2);    
    friend bool operator==(const Complex& p1, const Complex& p2);
    friend bool operator!=(const Complex& p1, const Complex& p2);    

    /* 输入输出运算符最好是以友元的方式重载 */
    friend ostream &operator<<(ostream &o, const Complex &p);
    friend istream &operator>>(istream &i, Complex& p);
};

以成员函数的方式重载

 

class Complex
{
private:
    double real, imag;

public:
    Complex() = default;
    Complex(double r, double i);
    ~Complex() = default;

    /* 赋值运算符只能以成员函数的形式重载 */
    Complex& operator=(const Complex &p);

    Complex operator+(const Complex &p);
    Complex operator-(const Complex &p);
    Complex operator*(const Complex &p);
    Complex operator/(const Complex &p);
   
    Complex operator++(int); // 后置++重载
    Complex operator--(int); // 后置--重载
    Complex &operator++();     // 前置++重载
    Complex &operator--();     // 前置--重载
    
    bool operator>(const Complex& p);
    bool operator<(const Complex& p);
    bool operator>=(const Complex& p);
    bool operator<=(const Complex& p);    
    bool operator==(const Complex& p);
    bool operator!=(const Complex& p);    

    ostream &operator<<(ostream &o);
    istream &operator>>(istream &i);
};

若以成员函数的方式重载输入输出运算符则在使用时会别捏,因为重载的函数中第一个参数是
this指针,所以在使用运算符时,第一个传入的参数应该是类类型,第二个参数才是流类型。

int main(int argc, char const *argv[])
{
    Complex p1;
/* 
    输入输出运算符最好是用友元的方式重载,不然用起来很别扭
    不符合正常的用法 
*/
    /* 成员函数方式重载 */
    p1 >> cin;
    p1 << cout << endl;
    /* 友元函数方式重载 */
//    cin >> p1;
//    cout << p1 << endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值