RTTI(runtime type information Identification) 运行时类型识别

目标:

dynamic_cast运算符

typeid运算符   返回的是一个type_info对象

type_info


dynamic_cast

reinterpret_cast不做任何的对齐操作

()  c风格还是会做一些对齐操作的


class type_info {

public:

    virtual ~type_info();

    bool operator==(const type_info& rhs) const;

    bool operator!=(const type_info& rhs) const;

    int before(const type_info& rhs) const;

    const char* name() 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);

};

程序:

#include <iostream>
using namespace std;
 
class Shape
{
public:
    virtual void Draw() = 0;
    virtual ~Shape() {}
};
 
class Circle : public Shape
{
public:
    void Draw()
    {
        cout<<"Circle Draw ..."<<endl;
    }
};
 
class Square : public Shape
{
public:
    void Draw()
    {
        cout<<"Square Draw ..."<<endl;
    }
};
 
int main(void)
{
    Shape* p;
    Circle c;
 
    p = &c;
    p->Draw();
 
    //以下两种的效率都不如上面来得快
 
 
    //如果右击  属性  把运行时类型识别给关了那就不行了 而且要有虚函数,不然不是安全的
    if (dynamic_cast<Circle*>(p))
    {
        cout<<"p is point to a Circle object"<<endl;
        Circle* cp = dynamic_cast<Circle*>(p);        
    ​    ​//应用在虚函数中,是安全的向下转型  是在运行时识别的
        cp->Draw();
    }
    else if (dynamic_cast<Square*>(p))
    {
        cout<<"p is point to a Square object"<<endl;
    }
    else
    {
        cout<<"p is point to a Other object"<<endl;
    }
 
    cout<<typeid(*p).name()<<endl;
    cout<<typeid(Circle).name()<<endl;
    ​//typeid可以用在类型或者对象上面
    if (typeid(Circle).name() == typeid(*p).name())
    {
        cout<<"p is point to a Circle object"<<endl;
        ((Circle*)p)->Draw();
    }
    else if (typeid(Square).name() == typeid(*p).name())
    {
        cout<<"p is point to a Circle object"<<endl;
        ((Square*)p)->Draw();
    }
    else
    {
        cout<<"p is point to a Other object"<<endl;
    }
 
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值