微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我正在阅读 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)).

原文地址:https://www.jb51.cc/c/112972.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐