use*_*587 -3 c++ visual-c++ c++11
下面是一个代码部分,无法根据数组是否为静态来检索数组的大小.
struct foo
{
static const char* const a[30];
const char* const b[30];
const int ia = __countOf(a) // compiles
const int ib = __countOf(b) // has compile errors related to initialization
};
Run Code Online (Sandbox Code Playgroud)
上面的最小例子确实编译了......
但你真正要问的是"当我引用foo :: b时为什么不编译?"
这是因为所有const成员必须在构造函数中初始化(实际上在构造函数的初始化列表中,而不是在正文中).
从c ++ 11开始,您可以在类定义中提供默认值:
#include <iostream>
struct foo
{
static const char* const a[30]; // compiles
const char* const b[30] = {"Hello", "World" /*insert others here */ };
};
const char* const foo::a[30] = {
"Hello", "Cruel", "World", /* etc */
};
int main()
{
foo f;
std::cout << f.b[0] << std::endl;
std::cout << f.a[2] << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)