2015-09-06 79 views
4

我知道這可能是一個常見問題,而我之前也見過類似的問題。我試圖圍繞「通過const引用返回」東西來包裝我的頭。我似乎在這個看似簡單的例子被卡住:強制引用不是「已更新」

#include <iostream> 
using namespace std; 

class Test { 
public: 
    int x; 

    Test(): x(0) {}; 

    const int& getX() const { 
    return x; 
    } 
}; 

int main() { 
    Test t; 
    int y = t.getX(); 
    cout << y << endl; 
    t.x = 1; 
    cout << y << endl; // why not 1? 
} 

我明白,const int的&返回防止我設置t.x使用類似y=1,這是罰款。然而,我希望y在最後一行是1,但它仍然爲零,就好像getX()返回一個純int。這裏到底發生了什麼?

+1

'y'本身僅會從'複製的getX()',不會使'y'參考。所以你的期望是錯誤的。 –

回答

8

當你通過引用返回,你的安全,結果在整數y有沒有關係,從這一點上成員x。它只是t.x的副本,它在初始化點後的值不會以任何方式取決於t.x的值或狀態。

使用參考來觀察你的期望行爲:

#include <iostream> 
using namespace std; 

class Test { 
public: 
    int x; 

    Test(): x(0) {}; 

    const int& getX() const { 
    return x; 
    } 
}; 

int main() { 
    Test t; 
    const int &y = t.getX(); 
    cout << y << endl; 
    t.x = 1; 
    cout << y << endl; // Will now print 1 
} 
3

您將返回的const引用賦值給一個int變量,而您應該將它賦值給const int &如果您希望它被更新。現在它被複制。