自考新教材-p233

吃可爱长大的小学妹 提交于 2020-01-12 19:32:01

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

源程序:

#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;

}

运行结果:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!