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

前端之家收集整理的这篇文章主要介绍了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.f2er.com/c/112972.html

猜你在找的C&C++相关文章