c++ - std::list static_cast 派生迭代器

标签 c++ iterator stdlist

我有一个列表定义为:

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/

相关文章:

c++ - 将对象添加到 std::list 时调用对象的析构函数

c++ - 将本地类函数指针传递给 std::list::sort

c++ - 多次无法输入值

c++ - 如何根据对象的旋转计算位置偏移量,openGL,C++

c++ - snprintf 的逆函数

C++:我可以使用成员变量的迭代器并使其成为类之一吗?

c++ - 为什么 Visual Studio 在这种情况下不执行返回值优化 (RVO)

c++ - 为什么我应该在 unordered_map 参数前添加 '&'?

c++ - value_comp 和 * 位于迭代器之前

c++ - 在 C++ 中输出列表的 vector