对于下面的 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/