重载二进制操作的正确方法

The proper way to overload binary operation

本文关键字:方法 二进制 操作 重载      更新时间:2023-10-16

我是C++新手,所以,请放轻松:)我发现了两种不同的方法来重载 c++ 中的二进制运算符。

第一个(来自Robert Lafore的"面向对象编程C++"一书(:

class Distance
{
private:
    int value;
public:
    Distance() : value(0) {}
    Distance(int v) :value(v) {}
    Distance operator+(Distance) const;
};
Distance Distance::operator+(Distance d2) const
{
    return Distance(value+d2.value);
}

另一个,使用朋友功能(来自互联网(

class Distance
{
private:
    int value;
public:
    Distance() : value(0) {}
    Distance(int v) :value(v) {}
    friend const Distance operator+(const Distance& left, const Distance& right);
};
const Distance operator+(const Distance& left, const Distance& right)
{
    return Distance(left.value + right.value);
}

所有这些情况都可以编写如下代码:

Distance d1(11);
Distance d2(5);
Distance d3 = d1 + d2;

我的问题:这些案例的主要区别是什么?也许有一些优点或缺点。还是某种"良好的编程礼仪"?

提前感谢您的智慧! :)

Distance可以从int隐式转换。然后,第二种样式可以将opeartor+与用作右操作数的对象一起使用Distance

Distance d1(11);
Distance d2(5);
Distance d3 = d1 + d2; //fine
Distance d4 = d1 + 5;  //fine
Distance d5 = 5 + d1;  //fine

第 1 种样式仅支持将 opeartor+ 与用作左操作数的 Distance 对象一起使用。

Distance d1(11);
Distance d2(5);
Distance d3 = d1 + d2; //fine
Distance d4 = d1 + 5;  //fine
Distance d5 = 5 + d1;  //fail

有几个细微的区别,包括:

非会员方式允许两者兼而有之

42 + Distance(42);
Distance(42) + 42;

而会员方式只允许

Distance(42) + 42;