2014-10-16 47 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