7

How to init constant integer array class member? I think that in same case classic array isn't best choice, what should I use instead of it?

class GameInstance{
    enum Signs{
        NUM_SIGNS = 3;
    };
    const int gameRulesTable[NUM_SIGNS][NUM_SIGNS]; //  how to init it?
public:
    explicit GameInstance():gameRulesTable(){};
};
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
vard
  • 2,142
  • 4
  • 30
  • 40

2 Answers2

7

In C++11, you could initialize const array member in an initialization list

class Widget {
public:
  Widget(): data {1, 2, 3, 4, 5} {}
private:
  const int data[5];
};

or

class Widget {
    public:
      Widget(): data ({1, 2, 3, 4, 5}) {}
    private:
      const int data[5];
    };

useful link: http://www.informit.com/articles/article.aspx?p=1852519

http://allanmcrae.com/2012/06/c11-part-5-initialization/

billz
  • 44,644
  • 9
  • 83
  • 100
6

Make it static?

class GameInstance{
    enum Signs{
        NUM_SIGNS = 3};
    static const int gameRulesTable[2][2];
public:
    explicit GameInstance(){};
};

...in your cpp file you would add:
const int GameInstance::gameRulesTable[2][2] = {{1,2},{3,4}};
Russ Freeman
  • 1,480
  • 1
  • 8
  • 6
  • Unfortunately my compiler doesn't allow this. He said that there is multiple array declaration. – vard Nov 30 '12 at 13:12
  • 2
    @vard 'const int GameInstance::gameRulesTable[2][2] = {{1,2},{3,4}};' - this should be in a .cpp file. – Stals Nov 30 '12 at 13:30