【问题标题】:Calling a function in an operator overload?在运算符重载中调用函数?
【发布时间】:2014-10-16 07:14:23
【问题描述】:

我有一个 A 类,

class A{

private:
   int num;
public:
   A(int n){ num = n; };
   int getNum(){
       return num;
   }
   A operator+(const A &other){
       int newNum = num + other.getNum();
       return A(newNum);
   };
};

为什么other.getNum() 会报错?我可以很好地访问其他 (other.num) 中的变量,但似乎我永远无法使用其他任何函数。

我得到的错误类似于

无效参数:候选者是 int getNum()。

我可以写int test = getNum(),但不能写int test = other.getNum(),但我几乎可以肯定我能够以某种方式调用other.getNum()

我是否忽略了什么?

【问题讨论】:

标签: c++ class overloading


【解决方案1】:

其他标记为 const。因此,只能在其上调用 const 方法。要么使其他非 const 或使 getNum 成为 const 方法。在这种情况下,使getNum const 将是可行的方法。

您可以在 this 上调用 getNum 的原因是因为这不是 const。使方法 const 有效地使 this 指针变为 const。

【讨论】:

  • operator+ 也应该是 const,因为它不会改变 *this。
猜你喜欢
  • 2011-01-27
  • 1970-01-01
  • 2017-03-12
  • 1970-01-01
  • 1970-01-01
  • 2013-02-06
  • 2013-08-02
  • 2011-11-09
  • 1970-01-01
相关资源
最近更新 更多