自考新教材-p233
Posted duanqibo
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自考新教材-p233相关的知识,希望对你有一定的参考价值。
基类与派生类之间的互相转换,使用指针的情况
源程序:
#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的主要内容,如果未能解决你的问题,请参考以下文章