8

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(){};
};
3
  • Thanks for your comment, I looked this question, but those question was answered in 2008, and there was some discussion about possible new standart features, which was accepted later in 2011. Commented Nov 30, 2012 at 12:57
  • 3
    There is an answer for C++11 in that question. Commented Nov 30, 2012 at 12:59
  • 1
    @vard It's the answer by Flexo. Commented Nov 30, 2012 at 13:14

2 Answers 2

8

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/

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

Unfortunately my compiler doesn't allow this. He said that there is multiple array declaration.
@vard 'const int GameInstance::gameRulesTable[2][2] = {{1,2},{3,4}};' - this should be in a .cpp file.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.