我搜索了这个网站和谷歌,并没有找到任何解决我问题的方法。我现在正在尝试编写游戏,这个游戏包含玩家可以移动的地形图块地图。我想将磁贴存储在10x10阵列中,但是我在初始化阵列时遇到了问题。
我可以初始化数组的第一个维度,但错误在于在第一个for循环中初始化第二个维度。
以下是我的代码:
//tile on the "map"
struct tile
{
char type;
bool isWall;
};
void initializeMap(tile * map)
{
int index1, index2;
for(index1 = 0; index1 < 10; index1++)
{
map[index1] = new tile[10];
for(index2 = 0; index2 < 10; index2++)
{
}
}
}
int main()
{
tile * tileMap = new tile[10];
initializeMap(tileMap);
return 0;
}
我收到此错误:
C:\Users\----\Desktop\TextGame.cpp||In function 'void initializeMap(tile*)':|
C:\Users\----\Desktop\TextGame.cpp|39|error: no match for 'operator=' in '*(map + ((unsigned int)(((unsigned int)index1) * 2u))) = (tile*)operator new [](20u)'|
C:\Users\----\Desktop\TextGame.cpp|9|note: candidates are: tile& tile::operator=(const tile&)|
||=== Build finished: 1 errors, 0 warnings ===|
答案 0 :(得分:4)
您正尝试使用以下命令将实际对象设置为指针:
map[index1] = new tile[10];
map
是tile*
。但是,map[index1]
是一个被尊重的tile*
,它实际上是tile
,不能等于tile*
给你的new tile[10]
。
因此,您的代码将更好地工作:
struct tile {
char type;
bool isWall;
};
/**
* Initialize the map
* @param map The array of tile pointers
*/
void initializeMap(tile** map) {
int index1, index2;
for (index1 = 0; index1 < 10; index1++) {
// Set each element of the tile* array
// to another array of tile pointers
map[index1] = new tile[10];
for (index2 = 0; index2 < 10; index2++) {
// Do Something
}
}
}
int main() {
// Create a pointer to a set of tile pointers
tile** tileMap = new tile*[10];
// Pass it to the initializer
initializeMap(tileMap);
return 0;
}
答案 1 :(得分:2)
注意:从技术上讲,这不是一个二维数组,是一个结构数组的数组。
说,这个注释反映了你的代码问题:你有一个数组数组,所以第一个分配应该分配一个数组,其内容是指向其他数组的指针:
tile** tilemap = new tile*[10];
for( std::size_t i = 0 ; i < 10 ; ++i )
tilemap[i] = new tile[10];
....
//Dealocation at program finish:
for( std::size_t i = 0 ; i < 10 ; ++i )
delete tilemap[i];
delete tilemap;
但是,如果您使用标准容器(例如std::vector
)而不是手动内存管理(这很容易出错),则可以改进代码:
std::vector<std::vector<tile>> tilemap( 10 );
for( std::size_t i = 0 ; i < 10 ; ++i )
tilemap.emplace_back( 10 );
答案 2 :(得分:1)
我建议使用std::vector
共享指针到tile。这将允许您拥有不同的图块并将它们存储到矢量中:
struct Tile; // As you declared it.
struct Water_Tile : public Tile;
struct Mountain_Tile : public Tile;
struct Desert_Tile : public Tile;
// ...
typedef std::vector< boost::shared_ptr<Tile> > Tile_Container;
//...
Tile_Container my_world(10 * 10);
// ...
my_world[20] = new Water_Tile;
共享指针的一个很好的优点是它可以为你处理内存管理(删除)。