我有一个列表定义为:
std::list<CExcited*> mExcitedList;
兴奋被定义为:
class CExcited
{
public:
CExcited::CExcited(){}
virtual int getAnswer() = 0;
};
我有一个派生类:
class CExcitedA :: public CExcited
{
public:
CExcitedA::CExcitedA(){}
int getAnswer() {return 1;}
};
另一个:
class CExcitedB :: public CExcited
{
public:
CExcitedB::CExcitedB(){}
int getAnswer() {return 2;}
};
我在列表中添加了一些元素
CExcitedA* excitedA = new ExcitedA();
mExcitedList.add_back(excitedA);
CExcitedB* excitedB = new ExcitedB();
mExcitedList.add_back(excitedB);
当我迭代列表时,我无法弄清楚如何在运行时找出我添加的类。
我试图无济于事
for (std::list<Excited*>::iterator iter = mExcitedList.begin(); iter != mExcitedList.end(); iter++)
{
if (typeid(*iter) == typeid(CExcitedA*))
{
}
if (typeid(dynamic_cast<CExcitedA*>(*iter)) == typeid(CExcitedA*))
{
}
}
这似乎应该是直截了当的,但我无法得到它。
编辑从这里回答
CExcitedA* testA = dynamic_cast<CExcitedA*> (*iter);
if (testA != 0)
{
std::cout << "ES: " << dynamic_cast<CExcitedA*> (*iter)->getAnswer() << std::endl;
}
CExcitedB* testB = dynamic_cast<CExcitedB*> (*iter);
if (testB != 0)
{
std::cout << "EB: " << dynamic_cast<CExcitedB*> (*iter)->getAnswer() << std::endl;
}
答案 0 :(得分:1)
你已经有办法区分班级类型为什么不使用它?
for (std::list<Excited*>::iterator iter = mExcitedList.begin(); iter != mExcitedList.end(); iter++){
{
int classType = iter->getAnswer();
switch (classType) {
case 1: cout << "class A";
break;
case 2: cout << "class B";
break;
default: cout << "unknown class";
}
}
还有运行时类型ID检查: typeid(* iter).name()会给你“类名”