如何在构造函数中初始化 const 大小数组而不在 class 声明中明确说明大小?

How to initialize const size array in constructor without explicitly stating the size in class declaration?

我需要做类似

的事情
class foo {
  foo();
  int a[];
}

cpp 文件中的进一步内容:

foo::foo() : a{1,2,3,4} {}

特点:

  1. C++98 标准

  2. array 不是 int,初始化列表要长得多。虽然它的值在编译时是已知的,但它们会不时改变

编辑:当 new[] 用于内存分配时,另一种选择也适用,但是,再次明确声明数组大小是不可取的:

class foo {
  foo();
  int * a;
}

cpp 文件中的进一步内容:

foo::foo() {
  a = new[]; // impossible
  // filling the array with values
}

你不能这样做:数组的大小是数组 类型 的一部分,因此也是 class 的一部分。构造函数也是class的一部分。 class 需要先存在 ,然后 才能调用构造函数,因此构造函数 call 不会影响 class 定义。