* thomas:
Hi,
-------------code----------
#include<iostream>
using namespace std;
class maze{
public:
int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
void print(){
cout<<"hello"<<endl;
}
};
int main(){
maze ins;
ins.print();
}
------------code-----------------
The code cannot compile because of the declaration of the array "dir".
But I don't get it? why is that?
AFAIK there's no good reason, except historical accident, why the language is
that way.
In C++98 the only data members you can initialize directly in the declaration
are static const of integral or enumeration type (I'm using that standard's
terminology here -- as far as I'm concerned an enum is very integral!).
That means that in C++98 you have the same problem almost no matter the type, e.g.
class Amazing
{
double x = 5; // Nah!
};
One way out is to use a constructor initializer list, like
class InstanceData
{
private:
double x;
public:
InstanceData(): x( 5 ) {}
};
If, however, the data is constant and the same for all instances, as it seems
your 'dir' array will be, then you can declare it static const,
class ClassData
{
private:
static double const x;
public:
// Whatever
};
double const ClassData::x = 5;
where the last line, the value definition, needs to be in exactly one
compilation unit and exactly once, i.e., don't put it in a header file.
The corresponding for your maze:
class Maze
{
private:
static int const dir[4][2];
public:
// Whatever.
};
int const Maze::dir[4][2] =
{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
However, I suggest defining a class Point to handle those (x,y) values, instead
of doing indexing or whatever -- it will save much work.
Cheers & hth.,
- Alf