2012-08-31 53 views
0

我試圖儘可能使用SSCE我的問題,但它涉及多個在C++中定義的對象。他們是簡單的,但 - 我認爲它最好的,如果我進一步解釋之前分享我的代碼:修改一個對象與修改該對象的副本

#include <iostream> 
#include <vector> 

struct Cell { 
     bool visited; 
     Cell():visited(false) {} 
     void setVisited(bool val) {visited = val;} 
     bool beenVisited() {return visited;} 
}; 
struct Vector2D 
{ 
     int size; 
     std::vector<Cell> myVector; 
     Vector2D(int n): size(n), myVector(n*n) {} 
     Cell& getAt(int x, int y) {return myVector[((x * size) +y)];} 
}; 

int main() 
{ 
    Vector2D vec = Vector2D(1); 
    Cell cell= vec.getAt(0,0); 

    cell.setVisited(true); 
    cell = vec.getAt(0,0); 
    if (cell.beenVisited() == false) 
     std::cout << "Why is this not true like I set it a moment ago?\n"; 
} 

我道歉,真誠爲所有這一切,但它是需要做出點。正如你所看到的,我得到了At()我認爲是Cell對象,將其訪問的實例數據設置爲true,然後關閉到另一個單元格。那麼,爲什麼當我回到同一個單元時,發現訪問的值是錯誤的,而不是真的?!這就像它沒有註冊我的私人數據變化!

這樣做的最好方法是什麼?

感謝

+0

否。[_this_](http://ideone.com/2fSjR)是[SSCCE](http://sscce.org)。 27行代碼,與您的程序有相同的問題。 –

回答

3
Cell cell= vec.getAt(0,1); 

對象的副本。 使用

Cell& cell = vec.getAt(0, 1); 

或者乾脆

vec.getAt(0, 1).setVisited(true); 

編輯。

此代碼應該工作。

using namespace bob; 
Vector2D vec = Vector2D(5); 
vec.setAt(0,0, Cell(0,0)); 
vec.setAt(0,1, Cell(0,1)); 
vec.setAt(0,2, Cell(0,2)); 
Cell& cell= vec.getAt(0,1); 

cell.setVisited(true); 
Cell cell1 = vec.getAt(0,2); 
cell1 = vec.getAt(0,1); 
if (cell1.beenVisited() == false) 
{ 
    std::cout << "Why is this not true like I set it a moment ago?" << std::endl; 
} 

http://liveworkspace.org/code/53634eda052a07885d4e6c062a0fd302

+0

我想使用&運算符...但是當我嘗試它仍然打印輸出/顯示上面的行爲。使用運算符還有其他一些竅門嗎? (請記住getAT返回一個Cell&)。 – PinkElephantsOnParade

+0

@PinkElephantsOnParade已更新。 – ForEveR

+0

@PinkElephantsOnParade:在'Cell&'中,'&'不是一個運算符(運算符是函數)。這意味着'Cell'是一個參考。 –

0

永遠的答案是正確的 - 你需要存儲由getAt()在引用變量返回的值,而不是複製它變成一個值變量。

您可能會考慮顯式聲明不應該複製「Cell」類,這將有助於您更快地捕獲此類錯誤。這可以通過聲明一個私有拷貝構造函數來完成(沒有body);或者如果使用boost,則可以通過繼承基類「boost :: noncopyable」(docs for noncopyable)來完成。