温馨提示×

c++ typeid的作用是什么

c++
小亿
100
2024-02-01 16:27:41
栏目: 编程语言
C++开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

C++中的typeid是一个运算符,用于获取一个表达式的类型信息。它的作用是返回一个std::type_info对象,该对象包含了表达式的类型信息,包括类型的名称。

typeid通常与dynamic_caststd::type_info一起使用,用于在运行时识别对象的实际类型,从而实现多态性。

下面是typeid的使用示例:

#include <iostream>
#include <typeinfo>

class Base {
   virtual void foo() {}
};

class Derived : public Base {};

int main() {
   Base* basePtr = new Derived();

   // 使用typeid获取basePtr所指对象的类型信息
   const std::type_info& type = typeid(*basePtr);

   // 打印类型的名称
   std::cout << "Object type: " << type.name() << std::endl;

   // 使用typeid进行类型判断
   if (type == typeid(Base)) {
      std::cout << "Object is of type Base" << std::endl;
   }
   else if (type == typeid(Derived)) {
      std::cout << "Object is of type Derived" << std::endl;
   }

   delete basePtr;
   return 0;
}

输出结果:

Object type: class Derived
Object is of type Derived

在上面的示例中,typeid(*basePtr)返回的type_info对象的名称为"class Derived",表示basePtr所指的对象的实际类型是Derived

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:c++中typeid的作用是什么

0