2017-10-15 34 views
-2

我寫的自我指涉結構2個代碼:自我指涉結構

1:

struct node 
{ 

    int a; 
    struct node *link; 

}; 

int main() 
{ 

    struct node n; 

    n.a = 5; 

    cout<< n.a << "\t" ; 

    cout << n.link ; 

    return 0; 

} 

輸出:5 0x40185b`

第二:

struct node{ 

    int a; 
    struct node *link; 

}; 

int main(){ 

    struct node n; 

    n.a = 5; 

    cout << n.a << "\t"; 

    cout << *n.link ; 

    return 0; 

} 

輸出:錯誤:鏈接未在此範圍內聲明。

請告訴我代碼中發生了什麼?

爲什麼拋出垃圾值?

如何初始化自引用結構指針?

+1

'錯誤:鏈接並沒有在這個scope.'宣稱這是一個運行時錯誤?看起來不像。 – jpo38

+1

閱讀一本好的C++編程書,然後看看一些[C++參考](http://en.cppreference.com/w/cpp);你的問題需要一些[MCVE],並且在這裏是題外話 –

+2

有趣的是,我得到了一個完全不同的錯誤https://ideone.com/Y6QQzl – StoryTeller

回答

1

我想這是你想要做什麼:

int main(){ 

    struct node n; 
    n.a = 5; 
    n.link = NULL; // initialize the link 
    cout << n.a << "\t"; 
    cout << n.link; 

    return 0; 

} 

*(n.link)只會是有效的,如果n.link指向有效node對象。 和cout << *(n.link);只有在您聲明operator<<nodecout << n.link;因輸出地址而非值而有效)時纔有效。

舉例來說,這將運行得更好:

#include <iostream> 

struct node{ 
    int a; 
    node *link; // Note: no need to prefix with struct 
}; 

std::ostream& operator<<(std::ostream& str, const struct node& n) 
{ 
    str << n.a << "\t -> "; 
    if (n.link) 
     str << *n.link; 
    else 
     str << "NULL"; 

    return str; 
} 

int main(){ 

    node n1; // Note: no need to prefix with struct 
    node n2; // Note: no need to prefix with struct 

    n1.a = 5; 
    n1.link = &n2; 

    n2.a = 6; 
    n2.link = NULL; 

    cout << n1; 

    return 0; 

} 

它輸出5 -> 6 -> NULL

+0

因爲這是C++,所以你應該使用'node a1;',而不是'struct node a1'。如果你在底部寫了'std :: cout',你也可以刪除'using namespace std'。 –

+0

@MartinBonner:確實如此,修正了 – jpo38

+0

非常感謝您的幫助..... –