在main外部的函数中使用struct [英] Use a struct in a function outside of main
问题描述
要在main()之外的函数中使用struct,你能使用forward声明并在main()中定义它,还是必须在块之外定义?
<如果在
main()
中定义一个结构,它将隐藏结构的全局名称。因此, main()
之外的函数将只能引用全局名称。这个例子取自C ++ 2011草案,第9.1节p2: struct s {int a; };
void g(){
struct s; //隐藏全局结构s
//带有块范围声明
s * p; //指局部结构s
struct s {char * p; }; // define local struct s
struct s; //重新声明,没有效果
}
没有语法来引用本地从函数范围外部定义类型。因此,即使使用模板也会失败,因为没有办法表达模板的实例化:
template< typename F>空栏(F * f){f-> a = 0; }
int main(){
struct Foo {int a; } f = {3};
bar(& f); //在C ++ 98 / C ++ 03中失败,但在C ++中确定11
}
$ b b
实际上,这在C ++ 11中已经允许,如本 answer 中所述。
To use a struct in a function outside of main(), can you use forward declaration and define it in main(), or does it have to be defined outside of a block?
If you define a structure inside of main()
, it will hide the global name of the structure. So the function outside of main()
will only be able to reference the global name. This example is taken from the C++ 2011 draft, Section 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
}
There is no syntax to refer to the locally defined type from outside the function scope. Because of that, even using a template will fail, because there is no way to express the instantiation of the template:
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
}
Actually, this is now allowed in C++11, as explained in this answer.
这篇关于在main外部的函数中使用struct的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!