C++ 在对象初始化之前,获取const char*const a[30]的大小很难确定大小

C++ 在对象初始化之前,获取const char*const a[30]的大小很难确定大小,c++,c++11,visual-c++,C++,C++11,Visual C++,下面是一段代码,根据数组是否为静态数组检索数组大小时遇到问题 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 }; 上面的最小示例编译 但您真

下面是一段代码,根据数组是否为静态数组检索数组大小时遇到问题

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
};

上面的最小示例编译

但您真正想问的是“为什么当我引用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;
}
#包括
结构foo
{
静态常量char*常量a[30];//编译
const char*const b[30]={“你好”,“世界”/*在此处插入其他人*/};
};
常量字符*常量foo::a[30]={
“你好”、“残忍”、“世界”/*等*/
};
int main()
{
福福;

std::cout是描述问题的最佳方法吗?示例是编译的。请提供一个完整的错误消息。将错误消息文本从输出窗口(Alt-2)复制到您的问题。这是一个程序员错误。编译包括链接阶段,不是吗?@πάνταῥεῖ 问题中发布的代码也为我链接。没有任何引用缺少的成员定义。当然,如果没有任何引用,链接器不会抱怨。但是OP可能没有指出它实际上在某个地方被引用。@user1881587 WTH是
\u countof
?@user1881587抱歉,伙计,没有任何东西可以取消“暂停”锤子比询问问题之外的代码更快。这个问题已经被否决了(不是我!),我无法再进一步回答了。也许可以发布另一个问题,其中包含一个最小的、完整的程序(即15行)来说明你的问题?