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

时间:2019-04-09 11:39:30

标签: c++ binary overloading operator-keyword

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

还有一个,使用了朋友功能(来自Internet)

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;

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

预先感谢您的智慧! :)

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:2)

有一些细微的差异,包括:

非成员方式允许同时拥有两者

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

成员方式仅允许

Distance(42) + 42;
相关问题