2012-04-30 103 views
0

STRUCT考慮到一段代碼:C++:指針在結構定義問題

struct myStruct 
{ 
    myStruct *next; 
}; 

接下來是在結構中定義聲明結構的指針,是嗎?

什麼是 - 下一個 - 的實用程序?我如何使用它?

+2

這看起來像一個單獨鏈接列表。 –

+2

由於您將問題標記爲C++,因此我想指出,除了可能出於教育目的,您可能不需要自己創建(單獨)鏈接列表。您可以使用'std :: list'類模板爲您執行雜耍指針的繁重工作 - 只需將適合於將有效內容建模到模板的類型即可。 –

+1

但他可能是一名學生,需要學習數據結構。您不使用標準庫學習數據結構,而是爲了教育目的而編寫它們。 在生產代碼中,我會希望看到人們使用標準庫,除非他們有一個非常好的理由不要。 – CashCow

回答

4

好像它是鏈接列表的實現。

+1

不是一個實現,而是數據結構。 –

1

該指針的用途是您在myStruct中執行的任何操作。您可以使用此指針與其他myStruct結構體(通過指針)保持直接關係,並直接操縱它們(即像「知道」其他對象一樣)。

例如(請注意,所有意圖和目的,結構在C++是公共類),

class Test 
{ 
public: 
    doSomethingToTheOtherStruct() { 
    if(t != NULL) 
     t->touch(); 

    setTouched(bool touch) { 
    touched = touch; 
    } 

    setT(Test* other) { 
    t = other; 
    } 

    bool isTouched() const { 
    return touched; 
    } 

private: 
    Test* t; 
    bool touched; 
}; 

這個類有一些非常簡單的方法,如果能夠證明使用指針的力量。下面是一個使用它的例子。

#include <iostream> 
using namespace std; 
int main() 
{ 
    Test t1; 
    Test t2; 
    Test* t3 = new Test; 

    // Notice that we set the pointers of each struct to point to a different one 
    // This is not necessary, but is definitely more useful than setting it to itself 
    // since you already have the "this" pointer in a class. 
    t1->setT(&t2); 
    t2->setT(t3); 
    t3->setT(&t1); 

    cout<< t1.isTouched() << t2.isTouched() << t3->isTouched() << endl; 

    t1->doSomethingToTheOtherStruct(); 
    t2.doSomethingToTheOtherStruct(); 

    cout<< t1.isTouched() << t2.isTouched() << t3->isTouched() << endl; 

    delete t3; 

    return 0; 
} 

請注意此代碼的結果。 t1從未設置爲觸摸,但無意中(通過指針),t2t3變得「感動」。

2

如果您想將這些結構鏈接在一起以便稍後遍歷它們,您可以使用next。當然,讓myStruct中的其他成員更有意義。

例如:

struct myStruct 
{ 
    int  data; 
    myStruct *next; 
}; 

myStruct st_1; 
myStruct st_2; 

st_1.data = 1; 
st_2.data = 2; 

st_1.next = &st_2; //st_1.next->data is now 2 
1

事實上,它是一個指向同一類的指針,並且成員變量名爲「next」,這表明它是一個鏈表,正如其他人指出的那樣。

如果變量是一個指向同一個類的指針,但被稱爲「父」,它很可能是某種父/子關係。 (例如,具有也是小部件的父級的GUI小部件)。

你可能會質疑究竟是爲什麼你被允許這樣做:答案是指向數據-types都是一樣的大小,所以編譯器將已經知道它有多少字節需要這個指針。

出於同樣的原因,您可以在您的類(或結構體)中指向僅爲其聲明和未定義數據類型的類型。 (很常見)。