基类与派生类之间的互相转换,使用指针的情况

源程序:

p.p1 { margin: 0; font: 11px Helvetica }
p.p2 { margin: 0; font: 11px Helvetica; min-height: 13px }
span.Apple-tab-span { white-space: pre }

#include<iostream>

using namespace std;

 

class CBase

{

protected:

int n;

public:

CBase(int i):n(i){}

void Print()

{

cout<<“CBase:n=”<<n<<endl;

}

};

class CDerived:public CBase

{

public:

int v;

CDerived(int i):CBase(i),v(2*i){}

void Func(){};

void Print()

{

cout<<“CDerived:n=”<<n<<endl;

cout<<“CDerived:v=”<<v<<endl;

}

};

 

int main()

{

CDerived objDerived(3);

CBase objBase(5);

CBase *pBase = &objDerived;

 

 

CDerived *pDerived;

pDerived = &objDerived;

cout<<“使用派生类指针调用函数”<<endl;

pDerived->Print();

pBase=pDerived;

cout<<“使用基类指针调用函数”<<endl;

pBase->Print();

//pBase->Func(); //错误,通过基类指针不能调用派生类函数

//pDerived=pBase; //错误,派生类指针=基类指针

pDerived=(CDerived*)pBase; //强制类型转换,派生类指针=基类指针

cout<<“使用派生类指针调用函数”<<endl;

pDerived->Print();

return 0;

}

运行结果:

自考新教材-p233-风君雪科技博客