C++ 初始化非静态成员数组 [英] C++ Initializing Non-Static Member Array

查看:45
本文介绍了C++ 初始化非静态成员数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编辑一些旧的 C++ 代码,这些代码使用如下定义的全局数组:

I am working on editing some old C++ code that uses global arrays defined like so:

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 类的私有成员.但是,C++ 编译器不允许我在声明数据成员时对其进行初始化.

I want to make all of these arrays private members of the Robot class defined below. However, the C++ compiler does not let me initialize data members when I declare them.

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() 构造函数中初始化这六个数组的元素.除了一个一个地分配每个元素之外,还有什么办法可以做到这一点?

I want to initialize the elements of these six arrays in the Robot() constructor. Is there any way to do this other than assigning each element one by one?

推荐答案

如果您的要求确实允许,那么您可以将这 5 个数组作为类的 static 数据成员,并在 .cpp文件如下:

If your requirement really permits then you can make these 5 arrays as static data members of your class and initialize them while defining in .cpp file like below:

class Robot
{
  static int posLShd[5];
  //...
};
int Robot::posLShd[5] = {250, 330, 512, 600, 680}; // in .cpp file

如果这是不可能的,那么像往常一样使用不同的名称声明这个数组,并使用 memcpy() 作为构造函数中的数据成员.

If that is not possible then, declare this arrays as usual with different name and use memcpy() for data members inside your constructor.

编辑:对于非静态成员,可以使用下面的 template 样式(对于像 int 这样的任何类型).为了改变大小,同样简单地重载元素数量:

Edit: For non static members, below template style can be used (for any type like int). For changing the size, simply overload number of elements likewise:

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

数组初始化现在变得微不足道:

C++11

The array initialization has now become trivial:

class Robot
{
   private:
       int posLShd[5];
       ...
   public:
       Robot() : posLShd{0, 1, 2, 3, 4}, ...
       {}
};

这篇关于C++ 初始化非静态成员数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆