c++ typeid的作用是什么

   2024-11-05 3080
核心提示:C++中的typeid是一个运算符,用于获取一个表达式的类型信息。它的作用是返回一个std::type_info对象,该对象包含了表达式的类型

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 DerivedObject is of type Derived

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

 
举报打赏
 
更多>同类维修大全
推荐图文
推荐维修大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号