C++ typeid 不同类型打印 name

测试环境
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 = &sub;
  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
小结
当基类中存在虚函数时,引用或者指针解引用 能够识别出真实类型
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值