2014-10-16 13 views
0

我有一个类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()莫名其妙。

我可以俯视吗?

+1

'other'是一个常量引用,而'getNum'不是一个常量成员函数。 – Claudio 2014-10-16 07:37:33

+2

推荐阅读:** [我应该在哪个计算机科学/编程协议栈中发布?](http://meta.stackexchange.com/a/129632/165773)** – gnat 2014-10-16 07:40:45

回答

5

其他标记为const。因此,只有const方法可以被调用。要么使其他非const或使getNum const方法。在这种情况下,制作getNum常量是要走的路。

您可以拨打getNumthis的原因是因为这不是常量。有效地构造一个方法使得这个指针为常量。

+1

另外operator +应该是const,因为它没有改变*这个。 – 2014-10-16 14:55:50