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;
}
输出结果:
需要注意的是,无论上述哪种方法,都没有多态使用起来简便!