全局运算符和成员运算符的区别 [英] difference between global operator and member operator

查看:390
本文介绍了全局运算符和成员运算符的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

定义一个全局运算符之间有区别,它接受一个类的两个引用,并定义一个仅接受正确操作数的成员运算符。

Is there a difference between defining a global operator that takes two references for a class and defining a member operator that takes only the right operand?

Global:

class X
{
public:
    int value;
};

bool operator==(X& left, X& right) 
{
    return left.value == right.value;
};

会员:

class X
{
    int value;
    bool operator==( X& right) 
    {
        return value == right.value;
    };
}


推荐答案

成员操作符(通常声明为朋友)是因为左侧是执行操作的那一侧。 Obj :: operator + 适用于:

One reason to use non-member operators (typically declared as friends) is because the left-hand side is the one that does the operation. Obj::operator+ is fine for:

obj + 2

但适用于:

2 + obj

为此,你需要像下面这样:

it won't work. For this, you need something like:

class Obj
{
    friend Obj operator+(const Obj& lhs, int i);
    friend Obj operator+(int i, const Obj& rhs);
};

Obj operator+(const Obj& lhs, int i) { ... }
Obj operator+(int i, const Obj& rhs) { ... }

这篇关于全局运算符和成员运算符的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆