c++ - C++ 中的类型检查

标签 c++ casting typechecking

在 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/

相关文章:

c - 强制转换时条件表达式中的类型不兼容

types - 类型检查和类型系统的限制是什么?

java - ceylon 类型检查器 : How to obtain the typed syntax tree?

c++ - 尝试在 C++ 中使用 <filesystem> 显示文件时出错

c++ - 运算符 << 重载 C++

c++ - 使用 C++ 开发一个 Facebook 应用程序

java - 不兼容的类型 : inferred type does not conform to upper bound(s)

c++ - Antlr 和链接失败

c# - 试图将字符串解析为 DateTime 格式 "02/01/2010"dd/MM/yyyy 而不是 "1/2/2010 MM/dd/yyyy

c++ - : (int) blabla * 255. 99999999999997 或 round(blabla*255) 常识正确的是什么?