要在 main() 之外的函数中使用结构,是否可以使用前向声明并在 main() 中定义它,还是必须在 block 之外定义它?
最佳答案
如果在 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 中所述.
关于c++ - 在 main 之外的函数中使用结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12487370/