关于C++中RTTI与Java中RTTI的对比和使用

RTTI是”Runtime Type Information”的缩写,意思是运行时类型信息,它提供了运行时确定对象类型的方法。


在C++当中,RTTI的使用,主要是typeinfo头文件当中的typeid,它的使用方法如下:

#include <iostream>
#include <typeinfo>
using namespace std;
 
class A
{
public:
     void Print() { cout<<"This is class A."<<endl; }
};
 
class B : public A
{
public:
     void Print() { cout<<"This is class B."<<endl; }
};
 
struct C
{
     void Print() { cout<<"This is struct C."<<endl; }
};
 
int main()
{
     A *pA1 = new A();
     A a2;
 
     cout<<typeid(pA1).name()<<endl; // class A *
     cout<<typeid(a2).name()<<endl; // class A
 
     B *pB1 = new B();
     cout<<typeid(pB1).name()<<endl; // class B *
 
     C *pC1 = new C();
     C c2;
 
     cout<<typeid(pC1).name()<<endl; // struct C *
     cout<<typeid(c2).name()<<endl; // struct C
 
     return 0;
}

其中,typeid(object)返回的是一个type_info类,该类保存了object对象的一些元数据。type_info的结构如下:

class type_info
{
public:
    virtual ~type_info();
    bool operator==(const type_info& _Rhs) const; // 用于比较两个对象的类型是否相等
    bool operator!=(const type_info& _Rhs) const; // 用于比较两个对象的类型是否不相等
    bool before(const type_info& _Rhs) const;
 
    // 返回对象的类型名字,这个函数用的很多
    const char* name(__type_info_node* __ptype_info_node = &__type_info_root_node) const;
    const char* raw_name() const;
private:
    void *_M_data;
    char _M_d_name[1];
    type_info(const type_info& _Rhs);
    type_info& operator=(const type_info& _Rhs);
    static const char * _Name_base(const type_info *,__type_info_node* __ptype_info_node);
    static void _Type_info_dtor(type_info *);
};


在Java当中,RTTI的形式主要有三种:

(1)传统的类型转换(即常用的“Classb b =Classb )a”,其中b为a的子类);

(2)代表对象的类型的Class对象。通过查询Class对象可以获取运行时所需的信息;

(3)关键字instanceof

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值