C++ Initializing Non-Static Member Array

前端 未结 9 788
独厮守ぢ
独厮守ぢ 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

    To throw one other approach into the mix (and one that doesn't tell you to make the array data members static as most of the other answers do – I assume you know whether or not they should be static), here's the zero-overhead approach I use: Make static member functions and have them return std::array<> (or boost::array<> if your compiler is too old to come with a std:: or std::tr1:: implementation):

    class Robot
    {
        static std::array<int, 5> posLShd_impl() { std::array<int, 5> x = {{ 250, 330, 512, 600, 680 }}; return x; }
        static std::array<int, 5> posLArm_impl() { std::array<int, 5> x = {{ 760, 635, 512, 320, 265 }}; return x; }
        static std::array<int, 5> posRShd_impl() { std::array<int, 5> x = {{ 765, 610, 512, 440, 380 }}; return x; }
        static std::array<int, 5> posRArm_impl() { std::array<int, 5> x = {{ 260, 385, 512, 690, 750 }}; return x; }
        static std::array<int, 5> posNeck_impl() { std::array<int, 5> x = {{ 615, 565, 512, 465, 415 }}; return x; }
        static std::array<int, 5> posHead_impl() { std::array<int, 5> x = {{ 655, 565, 512, 420, 370 }}; return x; }
    
        std::array<int, 5> posLShd;
        std::array<int, 5> posLArm;
        std::array<int, 5> posRShd;
        std::array<int, 5> posRArm;
        std::array<int, 5> posNeck;
        std::array<int, 5> posHead;
    public:
        Robot();
    };
    
    Robot::Robot()
      : posLShd(posLShd_impl()),
        posLArm(posLArm_impl()),
        posRAhd(posRAhd_impl()),
        posRArm(posRArm_impl()),
        posNeck(posNeck_impl()),
        posHead(posHead_impl())
    { }
    
    0 讨论(0)
  • 2020-12-03 11:43

    you can either make it static, or use the new initialisation introduced in C++0x

    class Robot
    {
    private:
      int posLShd[5];
      static int posLArm[5];
      // ...
    public:
      Robot() :
        posLShd{250, 330, 512, 600, 680} // only C++0x                                                                                     
      {}
    
      ~Robot();
    };
    
    int Robot::posLArm[5] = {760, 635, 512, 320, 265};
    
    0 讨论(0)
  • Not really, although I agree with stefaanv's comment - if they were global previously, making them static would get you the "easy assignment", and they seem as though they may be const static at a glance.

    If these values are something you change occasionally, you might consider reading them in from an external file on class creation, such that you can avoid recompiles.

    You also might consider using std::vector instead of the fixed arrays for some of the features it provides.

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