typeid-4

typeid用户检查表达式的类型。

 typeid (expression)

typeid返回定义在标准头文件中常对象类型的引用,且返回值是可通过==和!=比较的.获得的对象可通过name()成员获取以空格结尾的数据类型或类名字符串。

#include <iostream>
#include <typeinfo>
using namespace std;

int main () {
  int * a,b;
  a=0; b=0;
  if (typeid(a) != typeid(b))
  {
    cout << "a and b are of different types:/n";
    cout << "a is: " << typeid(a).name() << '/n';
    cout << "b is: " << typeid(b).name() << '/n';
  }
  return 0;
}

 

typeid使用RTTI跟踪动态对象的类型在typeid运用于类时。当typeid运用于类型为多态的类,将返回最底层对象的类型。

#include <iostream>
#include <typeinfo>
#include <exception>
using namespace std;

class CBase { virtual void f(){} };
class CDerived : public CBase {};

int main () {
  try {
    CBase* a = new CBase;
    CBase* b = new CDerived;
    cout << "a is: " << typeid(a).name() << '/n';
    cout << "b is: " << typeid(b).name() << '/n';
    cout << "*a is: " << typeid(*a).name() << '/n';
    cout << "*b is: " << typeid(*b).name() << '/n';
  } catch (exception& e) { cout << "Exception: " << e.what() << endl; }
  return 0;

### C++ `typeid` 使用方法及示例 #### 什么是 `typeid` `typeid` 是 C++ 中的一个运算符,用于获取对象或类型的运行时类型信息 (RTTI, Run-Time Type Information)[^2]。它的返回值是一个 `std::type_info` 对象的常量引用,可以通过调用其成员函数来进一步操作。 #### 包含头文件 要使用 `typeid`,必须包含 `<typeinfo>` 头文件[^4]。 ```cpp #include <iostream> #include <typeinfo> // 必须包含此头文件 using namespace std; ``` #### 基本语法 `typeid` 支持两种形式: 1. **针对类型名**:`typeid(type)` 返回指定类型的 `std::type_info` 对象。 2. **针对表达式**:`typeid(expression)` 返回表达式的实际类型的 `std::type_info` 对象。 #### 静态类型 vs 动态类型 - 如果作用于非多态类型,则返回的是静态类型信息[^3]。 - 如果作用于具有虚函数的基类指针或引用,则可能返回动态类型信息(取决于具体实现)[^5]。 #### 示例代码 以下是几个典型的 `typeid` 应用场景: ##### 示例 1: 输出基本数据类型的名称 通过 `typeid` 获取变量的数据类型并打印出来。 ```cpp int main() { int a = 0; double b = 2.0; cout << "a type = " << typeid(a).name() << endl; // 输出 a 的类型 cout << "b type = " << typeid(b).name() << endl; // 输出 b 的类型 return 0; } ``` ##### 示例 2: 动态类型识别 当涉及继承关系时,`typeid` 能够区分基类和派生类的实际类型。 ```cpp class Base { public: virtual void foo() {} // 必须有虚函数才能启用 RTTI }; class Derived : public Base {}; void printTypeInfo(Base* obj) { cout << "Type of object: " << typeid(*obj).name() << endl; } int main() { Derived d; Base* ptr = &d; printTypeInfo(ptr); // 打印 Derived 类型的信息 return 0; } ``` ##### 示例 3: 结合 `std::any` 实现类型擦除 在现代 C++ 编程中,`typeid` 经常用作类型检查工具,在类型擦除机制下尤为有用。 ```cpp #include <iostream> #include <any> int main() { std::any a = 42; // 存储一个整数到 any 容器中 if (a.type() == typeid(int)) { // 检查存储的内容是否为 int 类型 cout << "Stored type is: " << typeid(a).name() << endl; } return 0; } ``` #### 注意事项 1. **性能开销**:由于涉及到运行时类型检测,频繁使用 `typeid` 可能会带来一定的性能损失。 2. **异常安全**:如果尝试访问未初始化的对象或者非法内存区域,可能会引发未定义行为。 3. **跨平台兼容性**:不同编译器对 `typeid().name()` 的输出格式可能存在差异,通常需要额外处理以获得可读性强的名字。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值