六十六课 C++中的类型识别

1、在面向对象时可能出现下面的情况

  • 基类指针指向子类对象
  • 基类引用成为子类对象的别名
Base* p = new Derived();
Base& r = *p;

静态类型:变量对象自身的类型。如Base*、Base&

动态类型:指针(引用)所指向对象的实际类型。如Derived

void test(Base* b)
{
  /*危险的转换方式*/
  Derived* d = static<Derived*>(b);
}

基类指针是否可以强制类型转换为子类指针取决于动态类型。

2、C++中如何得到动态类型?

  • 解决方案--利用多态
  1. 在基类中定义虚函数返回具体的类型信息
  2. 所有派生类都必须实现类型相关的虚函数
  3. 每个类中的类型虚函数都需要不同的实现

示例:动态类型识别

#include <iostream>
#include <string>

using namespace std;

class Base
{
public:
  virtual string type()
 {
   return "Base";
 }
};

class Derived : public Base
{
public:
 string type() 
 {
   return "Derived";
 } 
 void printf()
 {
   cout << "I'm a Derived." << endl;
 }
 
};

class Child : public Base
{
public:
  string type()
  {
    return "Child";
  }
};

void test(Base* b)
{

  if(b->type() == "Derived")
  {
    Derived* d = static_cast<Derived*>(b);
    d->printf();
  }

}

int main()
{
 Base b;
 Derived d;
 Child c;
 
 test(&b);
 test(&d);
 test(&c);
 
    return 0;
}

打印结果

多态解决的缺陷:

  • 必须从基类开始提供类型函数
  • 所有派生类都必须重写类型虚函数

3、C++中提供了typeid关键字用于获取类型信息

  • typeid关键字返回对应参数的类型信息
  • typeid返回一个type_info类对象
  • 当typeid的参数为NULL时,将抛出异常

4、typeid关键字的使用

 int i = 0;
 
 const type_info& tiv = typeid(i);
 const type_info& tii = typeid(int);
 
 cout<< (tiv == tii) << endl;
 

示例:typeid类型识别

#include <iostream>
#include <string>
#include <typeinfo>

using namespace std;

class Base
{
public:
 virtual ~Base()
 {
 }
};

class Derived : public Base
{
public:
 void printf()
 {
   cout << "I'm a Derived." << endl;
 }
 
};

void test(Base* b)
{
  const type_info& tb = typeid(*b);
  cout << tb.name() << endl;

}

int main()
{
 int i = 0;
 
 const type_info& tiv = typeid(i);
 const type_info& tii = typeid(int);
 
 cout<< (tiv == tii) << endl;
 
 Base b;
 Derived d;
 
 test(&b);
 test(&d);
 
  return 0;
}

打印结果

typeid 注意事项:

1、当参数为类型时,返回静态类型信息

2、当参数为变量时:

  • 不存在虚函数表,返回静态类型信息
  • 存在虚函数表,返回动态类型信息

3、不能的编译器返回的类型信息是不一样的

小结:

  1. C++中有静态类型动态类型的概念
  2. 利用多态能够实现对象的动态类型识别
  3. typeid是专用于类型识别的关键字
  4. typeid能够返回对象的动态类型信息

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值