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

标签 c++ operator-overloading

我正在阅读 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-() 作为成员函数会有什么不良后果,还有什么其他后果?

最佳答案

这里是 Fraction,运算符作为成员函数:

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里面没有成员函数operator-(当然,它连一个类都算不上)

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

Fraction z = 42 - x;

变成这样

Fraction z = Fraction(42) - x;

相当于 operator-( Fraction(42), x )

关于c++ - 重载运算符 - () 作为自由函数而不是成员函数的意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10958698/

相关文章:

c++ - 使用全局指针和自定义析构函数-如何避免内存泄漏?

c# - 如何重载泛型类的运算符?

c - 通过带有类型通知的宏重载 C 中的运算符

c++ - 这个声明是什么意思?异常()抛出()

不为右值引用调用 C++ move 构造函数

c++ - g++ L"string~"+ 运算符,类似于 Visual C++

c++ - 运算符重载的未解析外部符号

C++ Operator () 括号重载

c++ - 在 Box2D Web 中的 body 内定位圆形

c# - 仅存在于任务栏中的 Windows 应用程序