📅  最后修改于: 2023-12-03 15:29:53.350000             🧑  作者: Mango
C++中的typeid
运算符可以获取一个变量或表达式的类型信息,并返回一个常量type_info
对象。type_info
对象包含有关其表示类型的名称和其他信息,可以用于运行时类型识别和类型转换等操作。
typeid
运算符通常与dynamic_cast
关键字、虚函数表以及RTTI(运行时类型信息)一起使用。
typeid
运算符可以在变量或表达式前面放置,以获取其类型信息。具体语法如下:
typeid(expression)
expression
可以是一个变量、一个对象、一个表达式或一个类型名。它必须是一个真实的对象,而不是一个指针或引用。如果是一个指针或引用,则返回的类型信息是指针或引用的类型,而不是指向的对象的类型。如果是一个多态类型,则返回的类型信息是动态类型,而不是静态类型。
下面是一些使用typeid
运算符的示例:
#include <iostream>
#include <typeinfo>
using namespace std;
int main() {
int x = 1;
double y = 2.0;
int* p = nullptr;
class A {
public:
virtual void f() {}
};
class B : public A {};
A* q1 = new B();
A* q2 = new A();
const type_info& t1 = typeid(x);
const type_info& t2 = typeid(y);
const type_info& t3 = typeid(p);
const type_info& t4 = typeid(*q1);
const type_info& t5 = typeid(*q2);
const type_info& t6 = typeid(A);
const type_info& t7 = typeid(B);
const char* n1 = t1.name();
const char* n2 = t2.name();
const char* n3 = t3.name();
const char* n4 = t4.name();
const char* n5 = t5.name();
const char* n6 = t6.name();
const char* n7 = t7.name();
cout << "x is of type " << n1 << endl;
cout << "y is of type " << n2 << endl;
cout << "p is of type " << n3 << endl;
cout << "q1 is of type " << n4 << endl;
cout << "q2 is of type " << n5 << endl;
cout << "A is of type " << n6 << endl;
cout << "B is of type " << n7 << endl;
return 0;
}
输出结果为:
x is of type int
y is of type double
p is of type int *
q1 is of type class A
q2 is of type class A
A is of type class A
B is of type class B
从中可以看出,typeid
运算符可以返回变量或表达式的真实类型信息,包括它们的类名、指针类型等。如果表达式是一个多态类型,则返回的类型信息是动态类型,而不是静态类型。