测试环境
mac m1
Apple clang version 13.0.0 (clang-1300.0.29.30)
#include <iostream>
#include <typeinfo>
using std::cout;
using std::endl;
class Base{};
class Sub : public Base {};
class Base1{
public:
virtual ~Base1() {}
};
class Sub1 : public Base1 {};
int main() {
int a;
cout << "int a typeid name " << typeid(a).name() << endl;
bool b;
cout << "bool b typeid name " << typeid(b).name() << endl;
char c;
cout << "char c typeid name " << typeid(c).name() << endl;
double d;
cout << "double d typeid name " << typeid(d).name() << endl;
float f;
cout << "float f typeid name " << typeid(f).name() << endl;
Base base;
cout << "Base base typeid name " << typeid(base).name() << endl;
Sub sub;
cout << "Sub sub typeid name " << typeid(sub).name() << endl;
Base & base_ = sub;
cout << "Base & base_ typeid name " << typeid(base_).name() << endl;
Base* pbase = ⊂
cout << "Base* pbase typeid name " << typeid(pbase).name() << endl;
cout << "(*pbase) typeid name " << typeid(*pbase).name() << endl;
Base1 base1;
cout << "Base1 base1 typeid name " << typeid(base1).name() << endl;
Sub1 sub1;
cout << "Sub1 sub1 typeid name " << typeid(sub1).name() << endl;
Base1 & base1_ = sub1;
cout << "Base1 & base1_ typeid name " << typeid(base1_).name() << endl;
Base1 * pbase1 = &sub1;
cout << "Base1 * pbase1 typeid name " << typeid(pbase1).name() << endl;
cout << "*pbase1 typeid name " << typeid(*pbase1).name() << endl;
}
结果输出
int a typeid name i
bool b typeid name b
char c typeid name c
double d typeid name d
float f typeid name f
Base base typeid name 4Base
Sub sub typeid name 3Sub
Base & base_ typeid name 4Base
Base* pbase typeid name P4Base
(*pbase) typeid name 4Base
Base1 base1 typeid name 5Base1
Sub1 sub1 typeid name 4Sub1
Base1 & base1_ typeid name 4Sub1
Base1 * pbase1 typeid name P5Base1
*pbase1 typeid name 4Sub1
小结
当基类中存在虚函数时,引用或者指针解引用 能够识别出真实类型
|