C++ Initializing Non-Static Member Array

前端 未结 9 838
独厮守ぢ
独厮守ぢ 2020-12-03 11:18

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, 51         


        
9条回答
  •  孤街浪徒
    2020-12-03 11:41

    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
    

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

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

    The array initialization has now become trivial:

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

提交回复
热议问题