我遇到一个问题,其中私有类成员不会在成员函数中保存分配给它们的值。
我将mMapWidth和mMapHeight值初始化为0,然后在加载方法中将它们更新为5。此后不久,我调用 draw 方法,但在 for 测试中,mMapWidth和mMapHeight的值为0,和mMapCells是空的。
我按如下方式分配WorldMap对象:
main.h
WorldMap worldMap;
的main.cpp
WorldMap worldMap(graphics, &camera, &textureTileset);
worldMap.load();
worldMap.draw();
WorldMap对象的声明和定义如下:
worldmap.h
class WorldMap
{
public:
WorldMap();
WorldMap(Graphics*, Camera*, TextureManager*);
~WorldMap();
void draw();
void load();
private:
int mMapWidth = 0;
int mMapHeight = 0;
Graphics* pGraphics;
TextureManager* pTileSet;
Camera* pCamera;
};
worldmap.cpp
WorldMap::WorldMap(){}
WorldMap::WorldMap(Graphics* graphics, Camera* camera, TextureManager* tileset)
{
pGraphics = graphics;
pCamera = camera;
pTileSet = tileset;
mMapHeight = 0;
mMapWidth = 0;
}
WorldMap::~WorldMap(){}
void WorldMap::draw()
{
for (int tileY = 0; tileY < mMapHeight; ++tileY)
{
for (int tileX = 0; tileX < mMapWidth; ++tileX)
{
mMapCells[tileX + (tileY * mMapWidth)].draw();
}
}
}
void WorldMap::load()
{
mTileSize = 32;
mMapWidth = 5;
mMapHeight = 5;
mMapCells.reserve(mMapWidth * mMapHeight);
for (int tileY = 0; tileY < mMapHeight; ++tileY)
{
for (int tileX = 0; tileX < mMapWidth; ++tileX)
{
Cell* cell = new Cell();
cell->initialize(pGraphics, 32, 32, 5, pTileSet);
cell->setX(tileX * 32);
cell->setY(tileY * 32);
cell->setCurrentFrame(1);
mMapCells.push_back(*cell);
}
}
}
感谢您的关注。
答案 0 :(得分:0)
试试这个。
从main.h更改此行
WorldMap worldMap;
到WorldMap* worldMap;
在main.cpp
中这样做
worldMap = new WorldMap(graphics, &camera, &textureTileset);
worldMap->load();
worldMap->draw();
答案 1 :(得分:0)
首先定义你的worldMap两次,首先在main.h中,然后在main.cpp中。 但是你只需要一个全局的worldMap,你可以在main.h中这样写: extern WorldMap worldMap;
然后,包含main.h的其他文件可以根据需要使用此全局worldMap。