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

邮差的信 提交于 2019-12-11 05:39:22

问题


I need to do something like

class foo {
  foo();
  int a[];
}

Further in cpp-file:

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

Peculiarities:

  1. C++98 standard

  2. array is not int, initializing list is much longer. Though its values are known at compile time, they can change from time to time

EDIT: Another option is also suitable, when new[] is used for memory allocation, but, again, it is undesirable to state the array size explicitly:

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

Further in cpp-file:

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

回答1:


You cannot do that: The size of the array is part of the type of the array, and hence of the class. The constructor is also part of the class. The class needs to exist first before you can call constructors, so the constructor call cannot influence the class definition.



来源:https://stackoverflow.com/questions/43254145/how-to-initialize-const-size-array-in-constructor-without-explicitly-stating-the

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!