在给定指向其基类的指针的情况下识别子类?

ExO*_*uhr 8 c++ dynamic-typing

假设我有一个抽象基类Parent和子类Child1和Child2.如果我有一个函数,接受家长*,是有办法(或许与RTTI?)在运行时,以确定它是否是一个Child1*或*CHILD2的功能实际收到?

到目前为止,我在RTTI的经验是,当foo是Parent*时,typeid(foo)返回typeid(Parent*),而不管foo是其成员的子类.

Ern*_*ill 6

您需要查看解除引用指针的typeid,而不是指针本身; 即,typeid(*foo),而不是typeid(foo).询问解除引用的指针将获得动态类型; 询问指针本身只会让你获得静态类型.


Pio*_*cki 5

你可以用std::dynamic_cast它.

Parent* ptr = new Child1();
if(dynamic_cast<Child1*>(ptr) != nullptr) {
    // ptr is object of Child1 class
} else if(dynamic_cast<Child2*>(ptr) != nullptr) {
    // ptr is object of Child2 class
}
Run Code Online (Sandbox Code Playgroud)

此外,如果你使用智能指针std::shared_ptr,你可以这样检查:

std::shared_ptr<Parent> ptr(new Child1());
if(std::dynamic_pointer_cast<Child1>(ptr) != nullptr) {
    // ptr is object of Child1 class
} else if(std::dynamic_pointer_cast<Child2>(ptr) != nullptr) {
    // ptr is object of Child2 class
}
Run Code Online (Sandbox Code Playgroud)