在C Intitialzing数组++类,并修改的左值问题 [英] Intitialzing an array in a C++ class and modifiable lvalue problem
问题描述
我有一个基本的C ++类.The头看起来是这样的:
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;
};
现在的类cpp文件里面我想用类构造像这里面的默认值,并初始化的_ageGroupArray [5]:
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)
{
}
做这件事我收到的Ex pression必须修改的左值关于_ageGroupArray line.So是完全不可能初始化在构造一个数组对象?我发现的唯一的解决办法是定义范围之外的标识符阵列。任何澄清,这将是极大的AP preciated。
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.
推荐答案
在当前的标准,因为你已经注意到了,你无法初始化与初始化列表的语法构造一个成员数组。有一些解决方法,但没有人真的是pretty:
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};
这篇关于在C Intitialzing数组++类,并修改的左值问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!