加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 重载运算符 – ()作为自由函数的意义,而不是成员函数?

发布时间:2020-12-16 06:01:21 所属栏目:百科 来源:网络整理
导读:我正在阅读 the C++ FAQ.在那里,我发现操作符重载使用的指南中有一点: If you provide constructive operators,they should allow promotion of the left-hand operand (at least in the case where the class has a single-parameter ctor that is not mar
我正在阅读 the C++ FAQ.在那里,我发现操作符重载使用的指南中有一点:

If you provide constructive operators,they should allow promotion of the left-hand operand (at least in the case where the class has a single-parameter ctor that is not marked with the explicit keyword). For example,if your class Fraction supports promotion from int to Fraction (via the non-explicit ctor Fraction::Fraction(int)),and if you allow x – y for two Fraction objects,you should also allow 42 – y. In practice that simply means that your operator-() should not be a member function of Fraction. Typically you will make it a friend,if for no other reason than to force it into the public: part of the class,but even if it is not a friend,it should not be a member.

为什么作者写的是operator-()不应该是成员函数?

如果我将operator-()作为成员函数,还有什么后果呢?

解决方法

这里是作为成员函数的运算符的分数:
class Fraction
{
    Fraction(int){...}

    Fraction operator -( Fraction const& right ) const { ... }
};

有了它,这是有效的代码:

Fraction x;
Fraction y = x - 42;

其等效于x.operator-(Fraction(42));但这不是:

Fraction z = 42 - x;

因为42没有成员函数运算符(当然,它甚至不是一个类).

但是,如果您将运算符声明为自由函数,则转换操作将适用于其两个参数.所以这

Fraction z = 42 - x;

变成这样

Fraction z = Fraction(42) - x;

这相当于运算符 – (分数(42),x)).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读