2012-09-19 42 views
1

要在main()之外的函數中使用結構,能否使用forward聲明並在main()中定義它,還是必須在塊之外定義它?在主函數之外使用一個結構

+5

當你在main之外使用它時,是否有從main中定義它的特定優點? – chris

+2

,如果你按照你的建議去做,會發生什麼? –

回答

4

如果您在main()中定義了一個結構,它將隱藏結構的全局名稱。所以main()以外的功能只能引用全局名稱。這個例子是從C++ 2011草案第9.1節P2採取:

struct s { int a; }; 

void g() { 
    struct s;    // hide global struct s 
          // with a block-scope declaration 
    s* p;     // refer to local struct s 
    struct s { char* p; }; // define local struct s 
    struct s;    // redeclaration, has no effect 
} 

沒有語法指從功能範圍以外的到本地定義的類型。 正因爲如此,即使是使用模板會失敗,因爲沒有辦法表達的模板實例:

template <typename F> void bar (F *f) { f->a = 0; } 

int main() { 
    struct Foo { int a; } f = { 3 }; 
    bar(&f);       // fail in C++98/C++03 but ok in C++11 
} 

其實,這是現在允許C++ 11,在本answer解釋。

相關問題