【问题标题】:The proper way to overload binary operation重载二元运算的正确方法
【发布时间】:2019-04-09 11:39:30
【问题描述】:

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

还有一个,使用朋友功能(来自互联网)

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;

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

提前感谢您的智慧! :)

【问题讨论】:

标签: c++ binary overloading operator-keyword


【解决方案1】:

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 个数据成员怎么办?例如:int 英尺和浮点英寸(而不是 int 值)?我不能做 5+d1 ,反之亦然。那么,在这种情况下,两种选择有区别吗?
【解决方案2】:

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

非会员方式允许两者兼得

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

而会员方式只允许

Distance(42) + 42;

【讨论】:

  • 如果类中有超过 1 个数据成员怎么办?例如:int 英尺和浮点英寸(而不是 int 值)?我不能做 42+Distance(42) ,反之亦然。那么,在这种情况下,两种选择有区别吗?
猜你喜欢
  • 2017-03-24
  • 1970-01-01
  • 2012-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-30
  • 2015-07-23
  • 1970-01-01
相关资源
最近更新 更多