假设启用了运行时类型信息(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)
注意:如果您经常需要这样做,很有可能您的设计可以改进.
| 归档时间: |
|
| 查看次数: |
232 次 |
| 最近记录: |