2013-10-24 83 views
1

我通常在C中工作,但現在我必須使用C++。我有一個大文件,有很多重複,因爲我目前可以不循環遍歷dir_x到dirx_z。
1.是否有辦法讓這個類中的元素可尋址,就好像它是一個數組?我在最後一行給出了一個例子。
2.我現在指的我可以在類聲明中聲明一個數組,該數組稍後將被該類的元素填充?

Node * dir_x; 

爲紐帶,但什麼是真正的名字,所以我可以google一下?

class Node { 
public: 
     Node(int x, int y, int z){ 

       //Will be initialized to point to the next Node (neighbor) 
       //So will be holding elements of this same class! 
       dir_x = NULL; 
       dir_y = NULL; 
       dir_z = NULL; 
     } 

     //These are "links", but does anybody know the name to google it? 
     Node * dir_x; 
     Node * dir_x; 
     Node * dir_x; 
}; 

//Code snippet of a function: 
//current would be the node to traverse through the collection 
Node * current = someNode; 
//together with next 
Node * next = NULL; 
//Here the next node is actually set 
next = current->dir_x; 
//But I would like a generic way like below 
//to reduce code duplication by about a third: 
next = current->dir[i]; 
+0

你可以讓dir成爲Node * dir [3]。但是,你不應該有公共會員敦敦杜恩。 – IdeaHat

+1

這個詞是「指針」。 –

+0

你爲什麼試圖聲明三個同名的成員?這永遠不會起作用。 –

回答

0

你正在尋找一個鏈表

// this would not compile 
    Node * dir_x; 
    Node * dir_x; 
    Node * dir_x; 

    // i think you meant 
    Node * dir_x; 
    Node * dir_y; 
    Node * dir_z; 

你可以做的是

Node* dir[3]; // now this contains 3 pointers to node elements 

並根據需要

Node* node_x = node->dir[0]; 
    Node* node_y = node->dir[1]; 
    Node* node_z = node->dir[2]; 

除非node->dir[2]你可以用它應該是給你的seco nd節點。哪些也可以實現。

1

歡迎來到C++。你必須用C語言構建自己的許多東西都是C++標準庫的一部分。強烈建議使用這些組件,而不是自行構建。在這種情況下,您應該使用std::list而不是浪費所有時間和腦力來重塑已經完善了一百萬次的車輪。

至於你的問題,

//But I would like a generic way like below 
//to reduce code duplication by about a third: 
next = current->dir[i]; 

你可以實現你的Node類的operator[](size_t)。我猜這將是沿着這些線:

class Node 
{ 
public: 
    Node * mLeft; 
    Node * mRight; 

    Node& operator[] (size_t i) 
    { 
    if (!i) 
     return *this; 
    return (*mRight)[i-1]; 
    } 
}; 

當然,這只是一個博覽會。你需要做很多工作來處理範圍檢查,異常安全等等。

+0

我肯定會看看使用容器而不是手動實現C風格的鏈表 –