C++之双目运算符重载

运算符重载可以友元重载,也可以成员函数重载,但两者是不能共存的。因为这会造成二义性,再一次强调,计算机最讨厌的就是让他做选择。同时有的运算符只支持友元重载,有的则只能成员函数重载,在后面的详细说明中,再区分,先举个例子:

一、友元重载:

class Complex{
private:
    float _x;
    float _y;
public:
    Complex(float x = 0, float y = 0):_x(x), _y(y){}
    void dis(){
        cout << "( " << _x << "," << _y << " )" << endl;
    }
    friend Complex operator+(Complex &a, Complex &b){
        Complex t;
        t._x = a._x + b._x;
        t._y = a._y + b._y;
        return t;
    }
};

可以看到对于双目运算符重载的友元重载参数有两个,并且这里把友元的声明与定义都放在了类中,这样也是可以的。友元的实现位置不重要,但一定要在类中声明。

二、成员函数重载

class Complex{
private:
    float _x;
    float _y;
public:
    Complex(float x = 0, float y = 0):_x(x), _y(y){}
    void dis(){
        cout << "( " << _x << "," << _y << " )" << endl;
    }
    Complex operator+(Complex &a){
        Complex t;
        t._x = this->_x + a._x;
        t._y = this->_y + a._y;
        return t;
    }
    friend Complex operator+(Complex &a, Complex &b){
        Complex t;
        t._x = a._x + b._x;
        t._y = a._y + b._y;
        return t;
    }
};

int main()
{
    Complex a(10, 0), b(
  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值