我正在编辑一些使用如下定义的全局数组的旧 C++ 代码:
int posLShd[5] = {250, 330, 512, 600, 680};
int posLArm[5] = {760, 635, 512, 320, 265};
int posRShd[5] = {765, 610, 512, 440, 380};
int posRArm[5] = {260, 385, 512, 690, 750};
int posNeck[5] = {615, 565, 512, 465, 415};
int posHead[5] = {655, 565, 512, 420, 370};
我想让所有这些数组成为下面定义的 Robot 类的私有(private)成员。但是,C++ 编译器不允许我在声明数据成员时对其进行初始化。
class Robot
{
private:
int posLShd[5];
int posLArm[5];
int posRShd[5];
int posRArm[5];
int posNeck[5];
int posHead[5];
public:
Robot();
~Robot();
};
Robot::Robot()
{
// initialize arrays
}
我想在 Robot() 构造函数中初始化这六个数组的元素。除了一个一个地分配每个元素之外,还有什么方法可以做到这一点?
最佳答案
如果您的要求确实允许,那么您可以将这 5 个数组作为类的 static
数据成员,并在 .cpp 文件中定义时对其进行初始化,如下所示:
class Robot
{
static int posLShd[5];
//...
};
int Robot::posLShd[5] = {250, 330, 512, 600, 680}; // in .cpp file
如果这是不可能的,那么像往常一样用不同的名称声明这个数组,并使用 memcpy()
作为构造函数中的数据成员。
编辑:
对于非静态成员,可以使用以下 template
样式(对于任何类型,例如 int
)。要更改大小,只需同样重载元素数量:
template<size_t SIZE, typename T, T _0, T _1, T _2, T _3, T _4>
struct Array
{
Array (T (&a)[SIZE])
{
a[0] = _0;
a[1] = _1;
a[2] = _2;
a[3] = _3;
a[4] = _4;
}
};
struct Robot
{
int posLShd[5];
int posLArm[5];
Robot()
{
Array<5,int,250,330,512,600,680> o1(posLShd);
Array<5,int,760,635,512,320,265> o2(posLArm);
}
};
C++11
数组初始化现在变得微不足道了:
class Robot
{
private:
int posLShd[5];
...
public:
Robot() : posLShd{0, 1, 2, 3, 4}, ...
{}
};
关于C++ 初始化非静态成员数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5643923/