dimensional vector in class C++

I need to create a vector of vectors full of integers. However, I continuously get the errors:

error: expected identifier before numeric constant error: expected ',' or '...' before numeric constant

using namespace std;

class Grid {
  public:

  Grid();

  void display_grid();
  void output_grid();

  private:

  vector<int> row(5, 0);
  vector<vector<int> > puzzle(9, row);
  int rows_;
  int columns_;

};

You cannot initialize the member variables at the point where you declare them. Use an initialization list in the constructor for that:

Grid::Grid()
  : row(5,0), puzzle(9, row),
    rows_(5), columns_(9)
{
}

C++ class definitions are limited in that you cannot initialise members in-line where you declare them. It's a shame, but it's being fixed to some extent in C++0x.

Anyway, you can still provide constructor parameters with the ctor-initializer syntax. You may not have seen it before, but:

struct T {
   T() : x(42) {
      // ...
   }

   int x;
};

is how you initialise a member, when you might have previously tried (and failed) with int x = 42; .

So:

class Grid {
  public:

  Grid();

  void display_grid();
  void output_grid();

  private:

  vector<int> row;
  vector<vector<int> > puzzle;
  int rows_;
  int columns_;
};

Grid::Grid()
  : row(5, 0)
  , puzzle(9, row)
{
  // ...
};

Hope that helps.


You can't initialize a member in a class declaration unless it's const static , because in C++ no code is being run/generated when you are declaring a class. You'll have to initialize them in your constructor.

链接地址: http://www.djcxy.com/p/52064.html

上一篇: ASP.Net MVC3模型绑定错误

下一篇: 在C ++类中的三维向量