【C++】RTTI(runtime type information)

dynamic_cast运算符

dynamic_cast运算符能够将基类的指针或引用安全的转换为派生类的指针或者引用。转换失败,返回空地址。在dynamic_cast被设计之前,C++无法实现从一个虚基类到派生类的强制转换。dynamic_cast就是为解决虚基类到派生类的转换而设计的。

typeid运算符

typeid 运算符允许在运行时确定对象的类型。typeid 的结果是 const type_info&。 该值是对表示 type-id 或 expression 的类型的 type_info 对象的引用,具体取决于所使用的 typeid 的形式。

type_info类

type_info 类描述编译器在程序中生成的类型信息。 此类的对象可以有效存储指向类型的名称的指针。 type_info 类还可存储适合比较两个类型是否相等或比较其排列顺序的编码值。 类型的编码规则和排列顺序是未指定的,并且可能因程序而异。

class type_info {
public:
    type_info(const type_info& rhs) = delete; // cannot be copied
    virtual ~type_info();
    size_t hash_code() const;
    _CRTIMP_PURE bool operator==(const type_info& rhs) const;
    type_info& operator=(const type_info& rhs) = delete; // cannot be copied
    _CRTIMP_PURE bool operator!=(const type_info& rhs) const;
    _CRTIMP_PURE int before(const type_info& rhs) const;
    size_t hash_code() const noexcept;
    _CRTIMP_PURE const char* name() const;
    _CRTIMP_PURE const char* raw_name() const;
};
#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()
{
    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 << endl;
    cout << typeid(*p).name() << endl;
    cout << typeid(Circle).name() << endl;

    if (typeid(Circle).name() == typeid(*p).name())
    {
        cout << "p is point to a Circle object" << endl;
        ((Circle*)p)->Draw();//会做对齐操作   reinterpret_cast不做对齐操作
    }
    else if (typeid(Square).name() == typeid(*p).name())
    {
        cout << "p is point to a Square object" << endl;
    }
    else
    {
        cout << "p is point to a Other object" << endl;
    }
    return 0;
}

你可能感兴趣的:(C++,c++,开发语言)