dynamic_cast运算符
2017-03-23 本文已影响6人
Hassan_chao
将基类的指针或引用,安全的转换成派生类的指针和引用
#include <iostream>
using namespace std;
class A
{
public:
virtual ~A(){}//使用dynamic_cast时必要!
};
class B:public A
{
public:
B()
{
m_b = 12;
}
void foo(){
cout << "B:" << m_b << endl;
}
private:
int m_b;
};
int main()
{
A* a = new B();//按A构造,按B执行
B* b = dynamic_cast<B*>(a);
b->foo();
delete a;
system("pause");
return 0;
}