为什么我不能对另一个类的静态char []执行sizeof?

Ala*_*lan 5 c++ static sizeof

为什么以下代码会生成编译错误?


编辑:我的原始代码不清楚 - 我已将代码拆分为单独的文件...


First.h

class First
{
public:
    static const char* TEST[];

public:
    First();
};
Run Code Online (Sandbox Code Playgroud)

First.cpp

const char* First::TEST[] = {"1234", "5678"};

First::First()
{
    uint32_t len = sizeof(TEST); // fine
}
Run Code Online (Sandbox Code Playgroud)

确定First班级中的大小似乎很好,但是......

Second.h

class Second
{
public:
    Second();
};
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误: 'const char *[]': illegal sizeof operand

def*_*ode 8

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
Run Code Online (Sandbox Code Playgroud)

要使其按照您的意愿工作,您可以:

  • First::TEST数组的大小添加到其声明(static const char* TEST[2];)
  • 添加一个返回sizeof的新静态方法First::TEST.该方法不能内联,必须在First.cpp中定义.