在运算符重载中调用函数

Calling a function in an operator overload?

本文关键字:调用 函数 重载 运算符      更新时间:2023-10-16

我有一个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()

我是不是忽略了什么?

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

之所以可以在this上调用getNum,是因为这不是常量。使方法const有效地使this指针const。