2

When ever I try to initialize a multidimensional array I get the following error:

(20) : error C2059: syntax error : '{'

This is my code:

/*
 *      Tic-Tac-Toe
 *      Version 1.0
 *      Copyright (C) 2010 lolraccoon. All rights reserved.
*/
#ifndef GAME_H
#define GAME_H

#include <iostream>
using namespace std;

class Game
{
private:
    /*
     *      0 = NONE
     *      1 = HUMAN
     *      2 = COMPUTER
    */
    int board[3][3] = {0};
    char pieces[3] = {' ','X','O'};
public:
    void dispBoard();
};

#endif
lolraccoon
  • 91
  • 1
  • 2
  • 7
  • 12
    I was totally going to rip off your code until I realized you hd a copyright. Damn. – Ed S. Dec 04 '10 at 00:24
  • 1
    This is not related to it being a multidimensional array. You're trying to initialize a class variable. Can't do that. See my answer. – EboMike Dec 04 '10 at 00:26
  • 1
    Seriously. It's a reasonable question, has a short code example that explains the situation. Sure, the assumption on the problem is wrong, but that's why he's asking SO in the first place. +1 from me. – EboMike Dec 04 '10 at 00:29

3 Answers3

5

You cannot initialize a class variables (except for statics). There are other questions about that which explain the reasoning in detail, but just really quick - it would result in the compiler creating code in your constructor, which is against the nature of C++.

Here is a recent question about the same issue: Why is initialization of integer member variable (which is not const static) not allowed in C++?

Community
  • 1
  • 1
EboMike
  • 76,846
  • 14
  • 164
  • 167
1
int board[3][3] = {};

I don't know why people insist on writing the 0, it is not needed.

Blindy
  • 65,249
  • 10
  • 91
  • 131
1

This was not your only error. Classes are not to be used like that. U need a constructor to set values etc etc.

Try that :

#ifndef GAME_H
#define GAME_H

#include <iostream>
using namespace std;

class Game
{
 private:
  int board[3][3];
  char pieces[3];
 public:
  void dispBoard();
  Game()
  {
   board = { };
   pieces = {' ','X','O'};
  }
};

#endif

Keep in mind that gcc gave me :

:21: warning: extended initializer lists only available with -std=c++0x or -std=gnu++0x
:22: warning: extended initializer lists only available with -std=c++0x or -std=gnu++0x

And no I don't know how to fix those 2 warnings. IMHO play with C++ a bit more.