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

前端 未结 3 1374
一生所求
一生所求 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};
    
    0 讨论(0)
  • 2021-01-18 18:24

    try this:

    int ageDefault[]={20,32,56,43,72};
    memcpy(_ageGroupArray, ageDefault, sizeof(ageDefault));
    
    0 讨论(0)
  • 2021-01-18 18:27

    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.

    0 讨论(0)
提交回复
热议问题