I am trying to create a 2D array of objects in a class and then initializing each cell using a constructor from another class, but i'm getting an error and don't know how to fix it. Here are the classes:
Tile:
class Tile
{
public:
enum Type
{
Sea, Ship, Hit, Miss
};
Tile() {}
Tile (int X, int Y, Type c)
{
this->X = X;
this->Y = Y;
this->cell = cell;
}
void setType(Type c)
{
this->cell = c;
}
Type getType()
{
return cell;
}
void draw(bool hidden)
{
if (hidden == false)
switch (this->getType())
{
case Sea:
cout<<" ~ ";
break;
case Ship:
cout<<" s ";
break;
case Hit:
cout<<" X ";
break;
case Miss:
cout<<" o ";
break;
}
else
switch (this->getType())
{
case Hit:
cout<<" X ";
break;
case Miss:
cout<<" o ";
break;
default:
cout<<" ~ ";
break;
}
}
private:
Type cell;
int X,Y;
};
Class Board:
class Board
{
private:
Tile B[row][col];
int R, C;
public:
Board (Tile B[][col])
{
for (R = 0; R < row; R++)
for (C = 0; C < col; C++)
B[R][C] = new Tile(R, C, Tile::Sea);
}
};
The error i am getting is inside the constructor of the Board class. I believe it could be done using a vector but i am forced to use an array.
Tile B[row][col]is not possible unlessrowandcolare known at compile time. Otherwise I'd suggeststd::vector<std::vector<Tile>>. If you are "forced to use an array" then as I said, your dimensions must be known at compile time.newhere, justB[R][C] = Tile(R, C, Tile::Sea);Tile*you have an array ofTile. You only neednewwhen you want to dynamically allocate an object and get it's pointer.