需要 #include <typeinfo>
#include<iostream> #include <typeinfo> int main() { int i = 100; std::cout << typeid(int).name() << std::endl; std::cout << typeid(i).name() << std::endl; //返回类型、变量、对象的类型名称 //返回值类型:char const* int* a1[10]; int(*a2)[10]; std::cout << typeid(a1).name() << std::endl; std::cout << typeid(a2).name() << std::endl; return 0; }
#include<iostream> #include <typeinfo> class A{ virtual void func(){} }; class B :public A { void func() {} }; class C :public A { void func() {} }; void foo(A& ra) { if (typeid(ra) == typeid(B)) { //比较操作 //具有多态继承关系时,用来确定指针或引用实际的目标类型 std::cout << typeid(ra).name() << std::endl; std::cout << "B子类处理" << std::endl; } if (typeid(ra) == typeid(C)) { std::cout << "C子类处理" << std::endl; } if (typeid(ra) == typeid(A)) { std::cout << "A子类处理" << std::endl; } } int main() { B b; foo(b); std::cout << typeid(B).name() << std::endl; //class B return 0; }