c++ - 以未指定大小、空括号定义的静态数组?

标签 c++ class compiler-construction static-array

对于下面的 C++ 代码片段:

class Foo {
    int a[]; // no error
};

int a[];     // error: storage size of 'a' isn't known

void bar() {
    int a[]; // error: storage size of 'a' isn't known
}

为什么成员变量不也导致错误?这个成员变量是什么意思?

我正在通过 CodeBlocks 8.02 使用 gcc 3.4.5 版(mingw-vista 专用版)。

在 Visual Studio Express 2008 - Microsoft(R) C/C++ Optimizing Compiler 15.00.30729.01 for 80x86 上,我收到以下消息:

class Foo {
    int a[]; // warning C4200: nonstandard extension used : zero-sized array in struct/union - Cannot generate copy-ctor or copy-assignment operator when UDT contains a zero-sized array
};

int a[];

void bar() {
    int a[]; // error C2133: 'a' : unknown size
}

现在,这也需要一些解释。

最佳答案

C++ 语言只允许在非定义声明 中省略数组大小

extern int a[]; // non-defining declaration - OK in C++

int a[]; // definition - ERROR in C++

int a[5]; // definition - OK, size specified explicitly
int a[] = { 1, 2, 3 }; // definition - OK, size specified implicitly

总是需要非静态类成员声明来指定数组大小

struct S {
  int a[]; // ERROR in C++
};

虽然静态类成员声明可以省略大小

struct S {
  static int a[]; // OK in C++
};

(同一个成员的定义当然要指定大小)

与此行为的任何偏差只能通过编译器的扩展非标准行为来解释。也许您应该指定一些额外的编译器设置,以使其以更迂腐的方式运行。

关于c++ - 以未指定大小、空括号定义的静态数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2717671/

相关文章:

c++ - 二叉搜索树上的范围查询(递归)

C++ - 声明结构和类时不允许使用不完整类型

ruby-on-rails - 如何获取其值等于 ruby​​ 中给定参数的散列键?

c++ - 地址 (&) 和间接运算符的正确格式是什么

c++ - 使用不同 deploy.prototxt 文件的 Caffe C++ 示例出错

algorithm - LR(0) 和 SLR 解析有什么区别?

javascript - 什么是随机逻辑词法扫描器,什么是树遍历代码生成器?

c - 如何使用我刚刚从源代码构建的 GMP 库?

c++ - 做 while 循环和其他

C++ - 使用类名作为函数参数