C++ `typeid` 运算符
C++ typeid
运算符详解
typeid
是 C++ 提供的一个运算符,用于获取表达式或类型的类型信息。它是运行时类型识别(RTTI, Run-Time Type Information)的一部分,尤其在多态体系中被广泛使用。
1. 基本用法
typeid
的主要功能是获取类型的类型信息,可以作用于:
- 类型表达式:
typeid(T)
- 对象或表达式:
typeid(expression)
语法
typeid(expression)
typeid(type)
返回值
typeid
返回一个 const std::type_info&
,它是一个标准库中定义的类,用于描述类型信息。
示例代码
#include <iostream>
#include <typeinfo> // 必须包含头文件
using namespace std;int main() {int x = 10;double y = 5.5;cout << "Type of x: " << typeid(x).name() << endl;cout << "Type of y: " << typeid(y).name() << endl;return 0;
}
输出
Type of x: int
Type of y: double
注意:返回的类型名称可能会因编译器的实现不同而有所差异。例如,在 GCC 中可能输出
"i"
(表示int
),而在 MSVC 中可能直接输出"int"
。
2. 多态与动态类型
在多态体系中,typeid
可以用于获取指针或引用所指向对象的动态类型,而不仅仅是静态类型。
示例代码
#include <iostream>
#