目标:
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;
}