c++ - 在 main 之外的函数中使用结构

标签 c++

要在 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/

相关文章:

c++ - 在继承场景中使用基本结构作为函数参数

c++ - 零初始化类型

C++ 输入验证以避免破坏代码的能力

c++ - OpenCV C++ 如何知道每行排序的轮廓数?

c++ - Linux, openssl : where is THIRTY_TWO_BIT defined?

c++ - 在两个 Visual Studio C++ 项目之间扩展一个类

c++ - popen 调用中缺少数据

c++ - 仅通过按位运算反转(翻转)数字的最后 n 位

c++ - double 的重载比较以允许数值错误

c++ - 多重删除