将基类的指针或引用,安全的转换成派生类的指针和引用
#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;
}
网友评论