我有一个如下所述的课程
class Investment
{
private:
void init(BWAPI::UnitType type1, BWAPI::UpgradeType type2, BWAPI::TechType type3, int numOfItems);
UpgradeType upgradeType;
TechType techType;
UnitType unitType;
我的init方法就是这样
void Investment::init(BWAPI::UnitType type1, BWAPI::UpgradeType type2, BWAPI::TechType type3, int numOfItems)
{
if (type1 != NULL) {
this->unitType = type1;
this->type = type1.isBuilding() ? BUILDING_TYPE : UNIT_TYPE;
} else if (type2 != NULL) {
this->upgradeType = type2;
this->type = UPGRADE_TYPE;
} else if (type3 != NULL) {
this->techType = type3;
this->type = TECH_TYPE;
}
this->numOfItems = numOfItems;
}
我以这种方式得到我的物品(只能是三种可能类型中的一种)
const void* Investment::getItem() const
{
if (unitType != NULL)
return &unitType;
else if (upgradeType != NULL)
return &upgradeType;
else if (techType != NULL)
return &techType;
return NULL;
}
但是当我使用UnitType* type = (UnitType*) investment->getItem();
指针获取项目时会发生什么失去它的价值
当我调用type->getName().c_str();
它时返回一个空字符串
为了获得投资,我调用了一个 Stack 方法
// I have a stack of type std::vector<T*> stack;
T* getNext() {
clear();
for (int i = 0, leni = stack.size(); i < leni; i++) {
T* t = stack.at(i);
if (!t->isDone() && !t->isCanceled())
return t;
}
return NULL;
}