为什么以下代码会生成编译错误?
编辑:我的原始代码不清楚 - 我已将代码拆分为单独的文件...
First.h
class First
{
public:
    static const char* TEST[];
public:
    First();
};
First.cpp
const char* First::TEST[] = {"1234", "5678"};
First::First()
{
    uint32_t len = sizeof(TEST); // fine
}
确定First班级中的大小似乎很好,但是......
Second.h
class Second
{
public:
    Second();
};
Second.cpp
#include "First.h"
Second::Second()
{
    uint32_t len = sizeof(First::TEST); // error
    uint32_t elements = (sizeof(First::TEST) / sizeof(First::TEST[0])); // error
}
我收到以下错误: 'const char *[]': illegal sizeof operand
sizeof仅适用于完整类型.  const char* TEST[]在First.cpp中定义之前,它不是一个完整的类型.
sizeof(char*[10]) == sizeof(char*) * 10 == 40
sizeof(short[10]) == sizeof(short) * 10 == 20
// a class Foo will be declared
class Foo;
sizeof(Foo) == //we don't know yet
// an array bar will be defined.
int bar[];
sizeof(bar) == sizeof(int) * ? == //we don't know yet.
// actually define bar
int bar[/*compiler please fill this in*/] = { 1, 2, 3 };
sizeof(bar) == sizeof(int) * 3 == 12
// note bar is exactly the right size
// an array baz is defined.
int baz[4];
sizeof(baz) == sizeof(int) * 4 == 16
// initialize baz
int baz[4] = { 1, 2, 3 };
sizeof(bar) == sizeof(int) * 4 == 16
// note baz is still 4 big, the compiler doesn't control its size
要使其按照您的意愿工作,您可以:
First::TEST数组的大小添加到其声明(static const char* TEST[2];)First::TEST.该方法不能内联,必须在First.cpp中定义.