dynamic_cast

dynamic_cast 动态类型转换,必须有虚函数。

#include "stdafx.h"
#include <iostream>
using namespace std;

class Basic
{
public:
virtual void funOfBasic(){cout<<"this is the basic's fun"<<endl;}
};

class Derived:public Basic
{
public:
virtual void funOfDerived(){cout<<"this is the Derived's fun"<<endl;}
};

int _tmain(int argc, _TCHAR* argv[])
{
Basic *ptr1 = new Basic;
Basic *ptr2 = new Derived;

//只能向上转换,转换失败p1 = =NULL
Derived *p1 = dynamic_cast<Derived*>(ptr1);

//ptr2虽然是Basic类型指针但是指向Derived类型对象
//所以可以转换
Derived *p2 = dynamic_cast<Derived*>(ptr2);

if(p1)
{
cout<<"this is p1"<<endl;
p1->funOfBasic();
p1->funOfDerived();
}
if(p2)
{
cout<<"this is p2"<<endl;
p2->funOfBasic();
p2->funOfDerived();
}


return 0;
}

 虽然介绍的比较粗糙,但是依然希望能对路过的人有所帮助^_^

posted on 2012-06-02 12:47  kunkka_  阅读(154)  评论(0编辑  收藏  举报