c++ - 重载二元运算的正确方法

标签 c++ binary overloading operator-keyword

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

第一个(来自“C++ 中的面向对象编程”一书,Robert Lafore):

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);
}

还有一个,使用 friend 函数(来自互联网)

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

第一种方式只支持使用opeartor+,将Distance对象作为左操作数。即

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

关于c++ - 重载二元运算的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55592003/

相关文章:

C++:使用结构或枚举来重载构造函数之间的区别?

c++ - 了解 Dlib 内核实现

c++ - while 内打印增量计数变量值

c++ - include 如何使用软链接(soft link)?

c# - 将 jpeg 图像转换为十六进制格式

将由 0's and 1' 组成的十六进制转换为等效的二进制

来自二进制数的 C# 奇偶校验位

c++ - bit hack vs 循环内的条件语句

.net - IEnumerable.Equals 似乎调用了错误的 Equals 方法

c++ - 模板化类中的关系运算符重载 (C++)