error: too many initializers for const

error: too many initializers for const

为什么会出现以下错误

$ g++ -std=c++11 aaa.cpp 

aaa.cpp:15:2: error: too many initializers for ‘const aaaa::Fruit_List [0]’

};

^

编译以下代码时:

class aaaa
{  // without wrapping in class the code compiles fine
    const int a=7; // compiles fine

    struct Fruit_List{
        int index;
        int length;
    } const fruit_list[]={ // error: if I put 5 in braket the code compiles fine
        {0,3},
        {1,2},
        {2,5},
        {3,1},
        {4,7}
    };
};

int main()
{
    return 0;
}

如果我编写的代码没有在 class 中换行,它会编译得很好。给出数组的长度将抑制编译器错误。但是坚持将代码放在 class 中并避免给出数组大小,因为我以后可能会添加任何成员,我想将数组长度确定留给编译器。

强烈请避免链接到任何不合适的问题。

更新

感谢 juanchopanza 的评论。现在我知道即使是这个更简单的代码也无法编译:

class aaaa
{
    const int a[]={7,4,5};
};

int main()
{
    return 0;
}

正如您可能理解的那样,通过 将其包装成 class,您假设的常量不再是 引用对象的名称初始化常量时给出的固定值。相反,您现在要声明常量数据成员,它们就像非常量数据成员一样,并且在 class 中的每个实例中都独立存在。您提供的值只不过是一个 default 值,用于在构造函数中初始化常量成员。

考虑这个例子:

#include <ostream>
#include <iostream>

struct Demo {
  const int args[3];
  Demo() : args{1,2,3} {}
  Demo(int x) : args{x,x,x} {}
  Demo(int y, int z) : args{y, z} {}
};

int main(void)
{
  Demo d1;
  Demo d2(1,2);
  std::cout << d2.args[0] << ' ' << d2.args[1] << ' '
            << d2.args[2] << '\n';  // outputs "1 2 0"
  return 0;
}

并非所有构造函数都使用相同数量的值初始化 Demo::args。这是有效的,其余元素用零填充。您在 class 中为非静态数据成员提供的初始化只是语法糖,用于在每个构造函数中使用该值,在初始化列表中没有为该成员指定明确的值,因此上面的示例也可以写成这样:

#include <ostream>
#include <iostream>

struct Demo {
  const int args[3] = {1,2,3};
  Demo() {}
  Demo(int x) : args{x,x,x} {}
  Demo(int y, int z) : args{y, z} {}
};

int main(void)
{
  Demo d1;
  Demo d2(1,2);
  std::cout << d2.args[0] << ' ' << d2.args[1] << ' '
            << d2.args[2] << '\n';  // outputs "1 2 0"
  return 0;
}

成员 Demo::args 的初始化器不是 初始化器,而只是 一个 初始化器,而构造函数可以指定不同的那些。这很可能是不允许扣除大小的原因,就像您不能在非静态数据成员上使用 auto 一样。

如果您只是想在您的程序 运行 期间一直将具有常量值的单个命名实体的名称放入 class 提供的名称空间中,但不想要获得在某些构造函数中指定不同值的能力,请在 class.

中使用 static 常量