RTTI

RTTI


  • RTTI(runtime type information) 运行时类型信息

dynamic_cast


  • 安全的向下转型,用于多态类的向下转型

#include<iostream>
using namespace std;
class Shape
{
public:
    virtual void Draw()
    {
        cout << "Shape::Draw ..." << endl;
    }
};
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* cp = dynamic_cast<Circle*>(p);
    cp->Draw();
    Circle c;
    p = &c;
    if (dynamic_cast<Circle*>(p))
    {
        cout << "p is a point to Circle object." << endl;
    }
    else if (dynamic_cast<Square*>(p))
    {
        cout << "p is a point to Square object." << endl;
    }
    else
    {
        cout << "p is a point to other object." << endl;
    }
    return 0;
}

输出结果:
这里写图片描述

typeid运算符

将上例中的main函数修改如下:

int main(void)
{
    Shape *p;
    Circle c;
    p = &c;
    cout << typeid(Circle).name() << endl;
    cout << typeid(*p).name() << endl;
    if(typeid(Circle).name() == typeid(*p).name())
    {
        cout << "p is a point to Circle object." << endl;
    }
    else if(typeid(Square).name() == typeid(*p).name())
    {
        cout << "p is a point to Square object." << endl;
    }
    else
    {
        cout << "p is a point to other object." << endl;
    }
    return 0;
}

输出结果:
这里写图片描述

需要注意的是,无论上述哪种方法,都没有多态使用起来简便!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值