如何检查继承类的指针?

Now*_*wax 4 c++ polymorphism inheritance

假设我们有两个类:一个继承自A类的多态类A和类B.如何检查类A的指针是否指向B类的对象?

das*_*ght 6

假设启用了运行时类型信息(RTTI),您可以将指针强制转换为B*using dynamic_cast,并查看是否返回非空值:

A* ptr = ... // some pointer
if (dynamic_cast<B*>(ptr)) {
    // ptr points to an object of type B or any type derived from B.
}
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用typeid:

if (typeid(*ptr) == typeid(B)) {
    // ptr points to an object of type B, but not to a type derived from B.
}
Run Code Online (Sandbox Code Playgroud)

注意:如果您经常需要这样做,很有可能您的设计可以改进.