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

前端 未结 3 1376
一生所求
一生所求 2021-01-18 17:42

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

#pragma once
class DataContainer
{
public:
    DataContainer(void);
   ~DataContainer(void);
    int* g         


        
3条回答
  •  执念已碎
    2021-01-18 18:13

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

提交回复
热议问题