对于下面的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
}为什么成员变量没有引起错误呢?这个成员变量的含义是什么?
我使用的是从3.4.5 (mingw-vista special)到CodeBlocks 8.02的3.4.5版本。
在Visual Studio Express 2008 - Microsoft(R) C/C++ Optimizing 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
}现在,这也需要一些解释。
发布于 2010-04-27 07:46:31
C99支持被称为“灵活”数组成员的东西,该成员被允许作为结构的最后一个成员。当您动态分配这样的结构时,您可以增加从malloc()请求的数量,以便为数组提供内存。
一些编译器将其作为C90和/或C++的扩展添加。
所以你可以像下面这样写代码:
struct foo_t {
int x;
char buf[];
};
void use_foo(size_t bufSize)
{
struct foo_t* p = malloc( sizeof( struct foo_t) + bufSize);
int i;
for (i = 0; i < bufSize; ++i) {
p->buf[i] = i;
}
}您不能直接定义具有灵活数组成员的结构(作为局部变量或全局/静态变量),因为编译器不知道为它分配多少内存。
老实说,我不确定你是如何在C++的new操作符中使用这样的东西的--我认为你必须使用malloc()和placement new为对象分配内存,也许可以使用operator new的一些类/结构特定的重载……
发布于 2010-04-27 08:04:34
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++
};(当然,同一成员的定义必须指定大小)。
任何偏离此行为的行为都只能通过编译器的扩展非标准行为来解释。也许你应该指定一些额外的编译器设置,让它以更书生气的方式运行。
发布于 2010-04-27 07:40:23
class Foo {
int a[]; // OK in C, invalid in C++. Does not work with inheritance.
}; // Idea is that structure is "extended" indefinitely by an array.
// May work on your compiler as an extra feature.
int a[]; // error in C and C++: storage size of 'a' isn't known
void bar() {
int a[]; // error in C and C++: storage size of 'a' isn't known
}
extern int a[]; // OK: storage size may be declared later.
int a[5]; // declaration of size before use.未指定大小的数组类型不完整。8.3.4/1:
如果省略常量表达式,则D的标识符类型为“未知界T的派生-声明-类型-列表数组”,这是一个不完整的对象类型。
必须完成它才能参与定义,即a的定义必须包含大小规范或具有指定大小的数组的初始化。
https://stackoverflow.com/questions/2717671
复制相似问题