2012-03-20 27 views
0

我想設置類三角形的三個對象上的第二個和第三個角的值。如果明確完成的,這看起來是這樣的:C++ - for循環中的值未正確設置

triangle_mesh[0].set_vector_point2(vector_anchors[1]); 
triangle_mesh[1].set_vector_point3(vector_anchors[1]); 
triangle_mesh[1].set_vector_point2(vector_anchors[2]); 
triangle_mesh[2].set_vector_point3(vector_anchors[2]); 
triangle_mesh[2].set_vector_point2(vector_anchors[3]); 
triangle_mesh[0].set_vector_point3(vector_anchors[3]); 

工作!打印這些三角形,我得到(NB第一個彎道已經設置 - 這是不是一個問題):

triangle0 is (0, 0, -1) (1, 0, 0) (-0.5, -0.866025, 0) 
triangle1 is (0, 0, -1) (-0.5, 0.866025, 0) (1, 0, 0) 
triangle2 is (0, 0, -1) (-0.5, -0.866025, 0) (-0.5, 0.866025, 0) 

首先,雖然,這是醜陋的,其次,我有超過它必須推廣到案件三個三角形設置。我的代碼是:

for (int longitude = 0; longitude < num_longitudes; longitude++){ 
    SurfaceVector current_anchor = vector_anchors[1 + longitude]; 
    triangle_mesh[longitude].set_vector_point2(current_anchor); 
    triangle_mesh[(longitude + 1) % num_longitudes].set_vector_point3(current_anchor); 
} 

* n.b。 num_longitudes是3 *

我檢查一切我能想到的,但現在當我打印出我的三角形,我得到:

triangle0 is (0, 0, -1) (-0.5, -0.866025, 0) (-0.5, -0.866025, 0) 
triangle1 is (0, 0, -1) (-0.5, -0.866025, 0) (-0.5, -0.866025, 0) 
triangle2 is (0, 0, -1) (-0.5, -0.866025, 0) (-0.5, -0.866025, 0) 

沒有人有任何想法可能是想錯了?

編輯

上的三角形vector_point變量的指針,並設置這樣的:

void set_vector_point1(SurfaceVector vector_point) { vector_point1 = &vector_point; } 

回答

5

裏面就你的問題:

void set_vector_point1(SurfaceVector vector_point) { vector_point1 = &vector_point; } 

您指向一次臨時(函數調用完成後,vector_point停止存在)。更改它,以便正確複製SurfaceVector

+0

啊這是有道理的。但我希望我的三角形的指針指向vector_anchors向量的內存中相同的位置,而不是它的副本(兩者在我的程序中同樣長壽,所以我不想浪費內存存儲空間一切都是兩次)。 – tiswas 2012-03-20 14:32:34

+0

@tiswas,考慮使用一些智能指針,然後 - 像'boost :: shared_ptr' ... – Nim 2012-03-20 14:33:55

+0

嗯,我可以不只是@maitu建議,但直接傳遞vector_anchors的元素,而不是通過中間current_anchor .. ? – tiswas 2012-03-20 14:50:51

1

我會改變:

void set_vector_point1(SurfaceVector vector_point) { vector_point1 = &vector_point; } 

void set_vector_point1(SurfaceVector& vector_point) { vector_point1 = &vector_point; } 

或類似的東西。

在當前版本中,vector_point將是您傳遞的任何內容的副本,並且在您存儲指向不再存在的對象的指針後將不再存在。

在第二個中,vector_point是對該函數外部較長壽命的對象的引用。存儲一個指針就沒有問題,因爲當你使用指針時,對象仍然存在。

訣竅是確保對象的壽命比所有指向它的指針長。

此外:

感謝@Nim在下面的評論:

另外在for循環,其中行是:

SurfaceVector current_anchor = vector_anchors[1 + longitude]; 

這應該有可能是一個參考太..目前它也是一個副本。這樣你就可以編輯數組中的實際對象,而不是隨副本一起玩並扔掉它們。所以我會改變這一行爲:

SurfaceVector& current_anchor = vector_anchors[1 + longitude]; 
+0

仍然沒有幫助,他傳遞的東西(你已經更改爲引用)在for循環內局部範圍內,一旦退出循環,它就是一個懸掛指針。 – Nim 2012-03-20 13:29:56