C++:从抽象指针向量中获取继承的类型

C++ : get inherited type from abstract pointer vector

本文关键字:获取 继承 类型 向量 抽象 指针 C++      更新时间:2023-10-16

所以我有一个向量,它包含Component抽象类的指针
,假设我有两个从Component、foo和bar继承的类,有什么方法可以从这个向量中获得类型为"foo"的指针吗

    vector<Component*> components;
    class foo : Component;
    class bar : Component;
    components.push_back(new foo());
    components.push_back(new bar());

谢谢。

是的:

Component* c = components[0];
if (foo* f = dynamic_cast<foo*>(c)) {
    // use f
}
else {
    // c is not a foo. Maybe it's a bar, or something else
}

因此,如果你想写一个函数来查找foo*,你可以这样做(假设C++11):

foo* find_foo(const std::vector<Component*>& components)
{
    for (auto c : components) {
        if (foo* f = dynamic_cast<foo*>(c)) {
            return f;
        }
    }
    return nullptr;
}

强制转换dynamic_cast<foo*>将返回有效的foo*nullptr,它不会抛出。根据标准§5.2.7.9:

失败的强制转换为指针类型的值是所需结果类型的空指针值。

是的,您可以通过使用RTTI的概念来实现:-

#include <typeinfo>
//Using for loop iterate through all elements
if ( typeid(*iter) == typeid(Foo) )
  //You got the Foo object

但这在C++中几乎从来都不可取。