baidut
11/14/2014 - 3:04 PM

继承

继承

#include <iostream>
using namespace std;

// C++ 父类转为子类 
// 通过继承类实例化的基类指针可以CDerived * pD2 = dynamic_cast<CDerived * > (pB2); 转为继承类指针
//参考
// http://bbs.csdn.net/topics/260035544
// C++ 中dynamic_cast<>的使用方法 http://blog.csdn.net/gogogo/article/details/7073981
class CBasic{
public:
    virtual void disp(){
    	cout << "Basic" << endl;
    }
};
 
class CDerived : public CBasic {
public:
    // virtual 造成 dynamic_cast 执行期间错误
    void disp(){
    	cout << "Derived" << endl;
    }
};
 
int main() {
    CBasic * pB1 = new CBasic;
    CBasic * pB2 = new CDerived;
	pB1->disp();
    pB2->disp();
	cout << "父类指针转为子类指针" << endl;
    CDerived * pD1 = dynamic_cast<CDerived * > (pB1); //dynamic cast failed, so pD1 is null.  
    CDerived * pD2 = dynamic_cast<CDerived * > (pB2); //dynamic cast succeeded, so pD2 points to  CDerived object 
	if(pD1==NULL)cout<<"pD1==NULL"<<endl;//pD1->disp();
    pD2->disp();
    cout << "子类引用" << endl;
	CDerived & rD1 = dynamic_cast<CDerived &> (*pB1);  //dynamci cast failed, so throw an exception.   
    CDerived & rD2 = dynamic_cast<CDerived &> (*pB2);  //dynamic cast succeeded, so rD2 references to CDerived object. 
    //rD1.disp();;執行期間發生錯誤
    //rD2.disp();執行期間發生錯誤 和博文所说不符合
    return 0;
}