我有一个列表定义为:
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;
}
最佳答案
你已经有了区分类类型的方法,为什么不使用它呢?
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() 会给你“类名”
关于c++ - std::list static_cast 派生迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33427474/