简体   繁体   中英

C++ : get inherited type from abstract pointer vector

So i have a vector that holds pointers of a Component abstract class
, and let's say i have 2 inherited classes from component , foo and bar , is there any way to get the pointer with type "foo" from this vector?

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

Thanks.

Yep:

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
}

So if you want to write a function to find the foo* , you could do this (assuming 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;
}

The cast, dynamic_cast<foo*> will either return a valid foo* or nullptr , it will not throw. From the standard §5.2.7.9:

The value of a failed cast to pointer type is the null pointer value of the required result type.

Yes you can do it by employing concepts of RTTI:-

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

But that's almost never preferable in C++.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM