【问题标题】:Can somebody explain to me this code for overloading operators in c++? [duplicate]有人可以向我解释这段代码用于在 C++ 中重载运算符吗? [复制]
【发布时间】:2015-12-13 23:59:28
【问题描述】:

谁能帮我理解这段代码。我迷失了,因为教授刚刚在课堂上飞过它

class OpClass
  {
   private:
     int x;
   public:
     OpClassoperator+(OpClass right);
  };
OpClass OpClass::operator+(OpClass r)
{  OpClass sum;
sum.x = this->x + r.x; 
// or  sum.x = x + r.x;
return sum;
}

【问题讨论】:

  • 顺便说一句,教授(或您)在函数签名中犯了错误。正如您所展示的,这不是错误的语法,但确实无法完成几乎可以肯定的目的。应该是OpClass operator+(OpClass const& r) const

标签: c++ computer-science


【解决方案1】:
class OpClass
{
private:
  int x;
public:
 // declare operator+ - i.e. OpClass + OpClass
 // this function will be returning a copy since the expression
 // z = x + y does not modify x or y
 OpClass operator+(OpClass right); // should really be const!
};

OpClass OpClass::operator+(OpClass r)
{  
  // this part is actually garbage.
  OpClass sum;
  sum.x = this->x + r.x; 
  // or  sum.x = x + r.x;
  return sum;
}

这是正确完成的方法:

class OpClass
{
private:
  int x;
public:
 // always perform binary operations in terms of +=, -=, *= etc
 OpClass& operator+=(const OpClass& r) {
   x += r.x;
   return *this;
 }

};

// define binary operators in terms of unary

OpClass operator+(OpClass l, const OpClass& r)
{
  // note that the l argument is implicitly a copy
  l.x += r.x;
  return l;
}  

【讨论】:

  • 什么是“*this”?为什么你没有返回 x?
  • 当你用一元定义二元运算符时。当你可以直接从类中使用 x 时,为什么还要有一个对象 l?
  • 请注意 RicharHodges 在课堂外声明 operator+ 的选择。这允许左操作数按值传递,因此它可以用来代替组装结果的临时对象。我不同意这种选择(尤其是在 C++11 中),但它是有目的的(在某些情况下,在 C++11 之前)
猜你喜欢
  • 2011-08-20
  • 1970-01-01
  • 2011-05-31
  • 2015-07-14
  • 2011-02-28
  • 1970-01-01
  • 1970-01-01
  • 2022-12-16
相关资源
最近更新 更多