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

半城伤御伤魂 提交于 2019-12-01 19:23:24

问题


I have a basic C++ class .The header looks like this:

#pragma once
class DataContainer
{
public:
    DataContainer(void);
   ~DataContainer(void);
    int* getAgeGroup(void);
    int _ageGroupArray[5];
private:

     int _ageIndex;

};

Now inside the cpp file of the class I want to intialize the _ageGroupArray[5] with default values inside the class contructor like this:

#include "DataContainer.h"


DataContainer::DataContainer(void)
{

_ageGroupArray={20,32,56,43,72};

_ageIndex=10;
}

int* DataContainer::getAgeGroup(void){
return _ageGroupArray;
}
DataContainer::~DataContainer(void)
{
}

Doing it I am getting "Expression must be a modifiable lvalue" on _ageGroupArray line.So is it entirely impossible to initialize an array object in the constructor? The only solution I found was to define the array outside scope identifiers .Any clarification on this will be greatly appreciated.


回答1:


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



回答2:


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.




回答3:


try this:

int ageDefault[]={20,32,56,43,72};
memcpy(_ageGroupArray, ageDefault, sizeof(ageDefault));


来源:https://stackoverflow.com/questions/6647038/intitialzing-an-array-in-a-c-class-and-modifiable-lvalue-problem

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