让我们假设我们有两个类:一个多态类 A 和继承自类 A 的类 B。如何检查类 A 的指针是否指向类 B 的对象?
最佳答案
假设启用了 runtime type information (RTTI),您可以使用 B*
将指针转换到 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.
}
另一种方法是使用
typeid
:if (typeid(*ptr) == typeid(B)) {
// ptr points to an object of type B, but not to a type derived from B.
}
注意:如果您需要经常这样做,那么您的设计很有可能得到改进。
关于c++ - 如何检查继承类的指针?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23687137/