我的问题如下:
我正在设计一个小游戏;但是,我遇到了一个非常大的问题,我一直在尝试解决一段时间。从本质上讲,我想升级建筑物,如果使用有足够的点,但Building
对象中的数据正在损坏。唯一"假定"的对象是 .
buildings
vector
中的第一个分配对象建筑等级:
当我运行程序时,我面对黑屏(意味着它正确启动);当我调试时,我收到这样的错误:Access violation reading location 0x00000008
。表示已使用NULL
值。
class Building {
public:
int x = 0, y = 0;
vector<int> buildingID;
vector<int> upgradeCost;
int size = 4;
Building(vector<int> buildingID, int x, int y, vector<int> upgradeCost)
: buildingID(buildingID), x(x), y(y), upgradeCost(upgradeCost) { }
virtual void upgrade();
void drawTile(SDL_Rect, SDL_Surface*);
int buildingLevel = 1;
protected:
};
void Building::upgrade() {
if((buildingLevel+1) <= size)buildingLevel += 1;
}
void Building::drawTile(SDL_Rect drawRect, SDL_Surface* drawnTo) {
Tile::Tiles.at(buildingID[buildingLevel - 1]).drawTile(drawRect, drawnTo);
}
生成建筑物的函数:
void Level::generateTerrain() {
for (int i = 0; i < width; i++)
for (int j = 0; j < height; j++) {
int tile = rand()%100;
if (tile >= 25 && tile <= 28) this->tiles.at(i + (j*this->width)) = 2;
else if (tile < 24) this->tiles.at(i + (j*this->width)) = 1;
else if (tile == 29) {
this->addBuilding(Building(vector<int>{4, 3, 2, 1}, i * 75, j * 75, vector<int>{1, 1, 1, 1}), i, j);
}
else this->tiles.at(i + (j*this->width)) = 0;
}
}
添加建筑物的功能:
void Level::addBuilding(Building building, int x, int y) {
buildings.push_back(building);
tiles.at(x + (y*this->width)) = buildID(building.buildingID[building.buildingLevel-1], &buildings.at(buildings.size()-1));
}
最后是绘制瓷砖/建筑物的函数:
void Level::drawLevel(int x, int y, int width, int height, SDL_Surface* drawnTo, int beginningX, int beginningY) {
SDL_Rect tempRect;
tempRect.w = 75;
tempRect.h = 75;
for (int i = x; i <= (x + width); i++)
for (int j = y; j <= (y + height); j++) {
if (tiles.at(i + (j*this->width)).id == 999999) continue;
tempRect.x = (i*Tile::Tiles.at(tiles.at(i + (j*this->width)).id).tileSurface->w) + beginningX;
tempRect.y = (j*Tile::Tiles.at(tiles.at(i + (j*this->width)).id).tileSurface->h) + beginningY;
Tile::Tiles.at(tiles.at(i + (j*this->width)).id).drawTile(tempRect, drawnTo);
}
}
如果您需要更多代码片段,请直接询问。感谢您提供的任何帮助。
您的代码中唯一可疑的部分是您在 addBuilding() 中使用第二个参数中向量中元素的地址来构建 ID()。Vector 类在需要容量增长时重新分配它使用的内存,因此当发生这种情况时,现有元素可能不再位于指针指向的同一地址。