gpt4 book ai didi

c++ - 如何检查继承类的指针?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:23:24 28 4
gpt4 key购买 nike

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

最佳答案

假设 runtime type information (RTTI)已启用,您可以使用 dynamic_cast 将指针转换为 B*,然后查看是否返回非空值:

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com