您的位置:首页 > 编程语言 > C语言/C++

C++ 10 RTTI 运行时类型识别

2014-01-04 23:14 375 查看
来自:http://www.cppcourse.com/

01 dynamic_cast 安全的动态转型 需要运行时支持

用于运行时安全的向下转型 用于多态

02 typeid 返回一个 type_info对象



#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)) // 如果能够转型说明 类型是Circle 运行时类型识别技术
{
cout << "line: 40 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;
if (typeid(Circle).name() == typeid(*p).name())
{
cout << "#line 57 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: