在 C++ 中,我想知道对象的实际类型是否来自同一个类,而不是同一个类或派生类。这类似于以下 C# 代码:
Class Base
{
}
Class Child:Base
{
}
Base childObject = new Child();
If (childObject.GetType() == typeof(Child))
{
// do some code
}
谢谢!
最佳答案
有两种方法可以做到这一点。首先,您可以使用 typeid
运算符,它返回一个 type_info
结构,其中包含有关对象类型的信息。例如:
Base* ptr = /* ... */
if (typeid(*ptr) == typeid(DerivedType)) {
/* ... ptr points to a DerivedType ... */
}
请注意,您必须在此处使用 typeid(*ptr)
而不是 typeid(ptr)
。如果你使用 typeid(ptr)
,那么你会得到一个 Base*
的 type_info
对象,因为指针的类型是 Base*
不管它指向什么。
需要注意的重要一点是,这将检查 ptr
所指向的是否完全是一个 DerivedType
。如果 ptr
指向从 DerivedType
派生的类型的对象(可能是 EvenMoreDerivedType
),则此代码将无法正常工作。
检查您是否指向某种类型的对象的另一种方法是使用 dynamic_cast
运算符。 dynamic_cast
在运行时执行检查类型转换,如果转换成功,将产生一个有效指针,否则产生 nullptr
。例如:
Base* ptr = /* ... */;
auto* derived = dynamic_cast<DerivedType*>(ptr);
if (derived) {
/* ... points to a DerivedType ... */
}
这有一个额外的好处,如果 ptr
指向类似 EvenMoreDerivedType
的东西,转换仍然会成功,因为 EvenMoreDerivedType
继承自 DerivedType
.
最后,你有时会看到这样的代码:
Base* ptr = /* ... */
if (auto* derived = dynamic_cast<DerivedType*>(ptr)) {
/* ... points to a DerivedType ... */
}
这将 derived
指针限定为 if
语句的主体,并使用 C++ 中非零值计算为 true
的事实.我个人觉得这更容易阅读且不易出错,但请务必选择对您来说最简单的方法。
希望这会有所帮助!
关于c++ - C++ 中的类型检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4589226/