【发布时间】:2013-04-24 05:41:52
【问题描述】:
我正在开发一款 roguelike 游戏,并且我已将其设置为在 MOST 一个关卡上会有 3 个怪物。所以我有3个指向怪物的指针。它们都以 NULL 开头。
在怪物死后我应该如何将指针设置回 NULL?或者,也许我有错误的想法?本质上,我需要移除该怪物,直到该指针重新生成为另一个怪物。
我已经尝试了一些方法,但总是出现段错误。
我尝试使用擦除、删除,只需将其设置为 NULL,然后重新指向它。想不通。
我是这样设置指针的:
CreatureFactory myCreatures = CreatureFactory::instance();
Creature * pCreature1 = NULL;
Creature * pCreature2 = NULL;
Creature * pCreature3 = NULL;;
ItemFactory myItems = ItemFactory::instance();
Item * pItem1 = myItems.generateItem();
dl.placeInGame(personPlaying,randomGen);
int monsterCount = 0;
int turnCount = 0;
bool playingGame = true;
char playerController;
while (playingGame){
if ((turnCount % 2 == 0) && (personPlaying.getHP() < personPlay$
personPlaying.generateHP();
}
if (((turnCount % 3) == 0) && (monsterCount < 2)){
if(pCreature1 == NULL){
pCreature1 = myCreatures.generateCreature(4);
dl.placeInGame(pCreature1,randomGen);
monsterCount += 1;
}
else if(pCreature2 == NULL){
pCreature2 = myCreatures.generateCreature(4);
dl.placeInGame(pCreature2, randomGen);
monsterCount += 1;
}
else if(pCreature3 == NULL){
pCreature3 = myCreatures.generateCreature(4);
monsterCount += 1;
}
}
dl.dump();
personPlaying.dumpStats();
CreatureFactory code..
CreatureFactory & CreatureFactory::instance(){
static CreatureFactory myObj;
return myObj;
}
CreatureFactory::CreatureFactory(){
m_mtRandom.seed( time(NULL) );
fstream xmlFile;
xmlFile.open("critters.xml");
vector<XMLSerializable*> pObjects;
parseXML(xmlFile, pObjects);
XMLSerializable * pObject;
for(auto it = pObjects.begin(); it != pObjects.end(); it++){
pObject = (*it);
Creature * pCreature = dynamic_cast<Creature*>(pObject);
if (pCreature != NULL){
m_vCreatures.push_back(pCreature);
}
}
}
CreatureFactory::~CreatureFactory(){
}
Creature * CreatureFactory::generateCreature(int iMaxLevel) {
vector<Creature*> tempCreatures;
for(auto it = m_vCreatures.begin(); it != m_vCreatures.end(); it++){
if ((*it)->getLevel() <= iMaxLevel){
tempCreatures.push_back((*it));
}
}
int randomCreature = (m_mtRandom() % (tempCreatures.size() - 1));
Creature * pCreature = tempCreatures.at(randomCreature);
Creature * pReturnValue = new Creature(*pCreature);
return pReturnValue;
}
然后我会进行大量循环并使用大量类。指向这些怪物对象的指针通过了大约 6 或 7 个类。当 HP 达到 0 时,我需要将其中之一设置为 NULL。
谢谢
【问题讨论】:
-
请给我们看一些代码。另外,请使用适当的语言标签(例如
[c]或[c++])标记此问题。 -
为什么.. 这是一个普遍的问题。是的,对不起,我忘了标记 c++ 我会更新它。
-
这取决于指针是否“拥有”怪物,即它们是动态分配的,是否必须销毁?
-
不,他们不拥有怪物,也不是动态分配的。他们不应该被摧毁。我只需要它们为空白并准备指向另一个对象
-
monster1 = NULL;有什么问题?你的问题似乎很基本,所以我想还有更多。我认为您的段错误完全是由其他原因引起的。这是一个 XY 问题。像往常一样,给我们看一些代码。
标签: c++ pointers null segmentation-fault