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

时间:2013-04-21 21:05:34

标签: c++ dynamic-typing

假设我有一个抽象基类Parent和子类Child1和Child2。如果我有一个带有Parent *的函数,是否有办法(可能使用RTTI?)在运行时确定它是函数实际接收的Child1 *还是Child2 *?

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

3 个答案:

答案 0 :(得分:6)

您需要查看解除引用指针的typeid,而不是指针本身;即,typeid(* foo),而不是typeid(foo)。询问解除引用的指针将获得动态类型;询问指针本身只会让你得到静态类型,正如你所观察到的那样。

答案 1 :(得分: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
}

此外,如果您使用智能指针,例如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
}

答案 2 :(得分:3)

不确定

BaseClass *bptr = // whatever, pointer to base class
SubclassOne *safe_ptr_one = dynamic_cast<SubclassOne *>(bptr);
if (safe_ptr_one != nullptr) {
    // Instance of SubclassOne
} else {
    // not an instance of SubclassOne, try the other one
    SubclassTwo *safe_ptr_two = dynamic_cast<SubclassTwo *>(bptr);
    if (safe_ptr_two != nullptr) {
        // Instance of SubclassTwo
    } else {
        // it wasn't either one :'(
    }
}