简体   繁体   English

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

[英]Identifying a subclass given a pointer to its base class?

Suppose that I have an abstract base class Parent and subclasses Child1 and Child2. 假设我有一个抽象基类Parent和子类Child1和Child2。 If I have a function that takes a Parent*, is there a way (perhaps with RTTI?) to determine at runtime whether it's a Child1* or a Child2* that the function actually received? 如果我有一个带有Parent *的函数,有没有办法(可能有RTTI?)在运行时确定它是函数实际收到的Child1 *还是Child2 *?

My experience with RTTI here, so far, has been that when foo is a Parent*, typeid(foo) returns typeid(Parent*) regardless of the child class that foo's a member of. 到目前为止,我在RTTI的经验是,当foo是Parent *时,typeid(foo)返回typeid(Parent *),而不管foo是其成员的子类。

You need to look at the typeid of the dereferenced pointer, not the pointer itself; 您需要查看解除引用指针的typeid,而不是指针本身; Ie, typeid(*foo), not typeid(foo). 即,typeid(* foo),而不是typeid(foo)。 Asking about the dereferenced pointer will get you the dynamic type; 询问解除引用的指针将获得动态类型; asking about the pointer itself will just get you the static type, as you observe. 询问指针本身只会让你获得静态类型。

You can use std::dynamic_cast for this. 你可以使用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
}

Also if you are using smart pointers, like std::shared_ptr , you can check it like this: 此外,如果您使用智能指针,如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
}

Sure: 当然:

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 :'(
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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