开发者

Initialize a static const empty array

Is it possible to initialize a static const empty array, please see below code,

//CFoo.h
class CFoo
{
 public:
   CFoo();
   ~CFoo();

 public:
    static const int arr[];

};

//CFoo.cpp
const int arr[] = {0,1,2};

CFoo::CFoo(){}
CFoo::~CFoo(){}

EDIT:

It seems the code is valid, and for followup question, why I can't sizeof the static const array, li开发者_运维百科ke,

sizeof( CFoo::arr );

Is there any way I can sizeof CFoo::arr?

Thanks.


Yes; you need to qualify the name of the array:

const int CFoo::arr[] = {0,1,2};

The type of CFoo::arr is incomplete until the definition, so you are limited in how you can use it. For example, you cannot use it as the argument of sizeof. If you complete the declaration, then there's no problem:

struct CFoo {
    static const int arr[3];
};

Note, however, that this has maintainability issues because the size is specified in two separate places, and you likely won't get an error if there are fewer initializer values than the declared size of the array.


Yes.

const int CFoo:arr[] = {0,1,2};


sizeof is evaluated at compile time, not link time, so no - you can't leave it unspecified in the header yet have it evaluated before the definition.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜