在操作员超载中调用函数?

Gui*_*rum 0 c++ overloading class

我有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);
   };
};
Run Code Online (Sandbox Code Playgroud)

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

我得到的错误就是这样的

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

我可以写int test = getNum()但不是int test = other.getNum(),但我几乎可以肯定我能以other.getNum()某种方式打电话.

我忽略了什么吗?

Ben*_*Ben 5

其他是标记为const.因此,只能在其上调用const方法.要么制作其他非const,要么制作getNumconst方法.在这种情况下,制作getNumconst将是一种方法.

你可以打电话的原因getNumthis是因为这不是常量.使方法const有效地使this指针成为常量.