2014-09-19 106 views
-1

我可以知道爲什麼如果我從輸出中得到類似地址的東西。 任何人都可以告訴我如何使它作爲一個值輸出? 我是新來的指針,並要做鏈接列表。指針,無法打印值

struct node{ 
    int x; 
    node *next; 
}; 

int main(){ 

    node *root;  

    root = new node; 
    root->next = 0; 

    root->x = 5; 
    cout << root << endl; 

    return 0;   
} 
+0

相關:C++中的'structs'和'classes'沒有區別(默認可見性除外)。您應該爲'node'提供一個構造函數,以便設置'x = 0'和'next = NULL'。 – jww 2014-09-20 00:32:41

回答

3

你一樣賦值爲x

cout << root->x << endl; 
+0

謝謝很多朋友:) – Danzeeeee 2014-09-19 18:51:56

0

您還可以訪問的x值:

cout<<(*root).x<<endl; 
+0

非常感謝:) – Danzeeeee 2014-09-19 18:52:50

+2

你可以投票的答案,而不是謝謝:) – Rustam 2014-09-19 18:58:51

4

那麼,如果你真的想,你可以重載operator<<輸出節點類/結構的值,我目前不在編譯器附近,但我認爲它會這樣:

inline std::ostream& operator<< (std::ostream& os, const node* myNode) 
{ 
    os << myNode->x; 
    return os; 
} 

//用法:

std::cout << root << std::endl; 

但如果你只是想以最簡單的方式可能值,你總是可以只使用 操作符 - >如下圖所示:

std::cout << root->x << std::endl; 
+0

傳遞一個指針「cout」,並獲得它指向的價值是不尋常的,國際海事組織更好的方式是採取參考。 – GingerPlusPlus 2014-09-19 19:08:39

+0

感謝您的編輯,我沒有接近編譯器,並且希望確保答案是正確和清晰的。 – 2014-09-19 19:24:32