温馨提示×

c++ typeid的作用是什么

c++
小亿
85
2024-02-01 16:27:41
栏目: 编程语言

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

0