Intitialzing an array in a C++ class and modifiable lvalue problem

亡梦爱人 提交于 2019-12-01 19:26:39

In the current standard, as you have already noticed, you cannot initialize a member array in the constructor with the initializer list syntax. There are some workarounds, but none of them is really pretty:

// define as a (private) static const in the class
const int DataContainer::_age_array_size = 5;

DataContainer::DataContainer() : _ageIndex(10) {
   int tmp[_age_array_size] = {20,32,56,43,72};
   std::copy( tmp, tmp+_age_array_size, _ageGroupArray ); 
}

If the values in the array are always the same (for all object in the class) then you can create a single static copy of it:

class DataContainer {
   static const int _ageGroupArraySize = 5;
   static const int _ageGroupArray[ _ageGroupArraySize ];
// ...
};
// Inside the cpp file:
const int DataContainer::_ageGroupArray[_ageGroupArraySize] = {20,32,56,43,72};

You can Initialize a array when you Create/Declare it, not after that.

You can do it this way in constructor :

_ageGroupArray[0]=20;
_ageGroupArray[1]=32;
_ageGroupArray[2]=56;
_ageGroupArray[3]=43;
_ageGroupArray[4]=72;

It is important to know that this is Assignment & not Initialization.

try this:

int ageDefault[]={20,32,56,43,72};
memcpy(_ageGroupArray, ageDefault, sizeof(ageDefault));
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!