自考新教材-p233
基類與派生類之間的互相轉(zhuǎn)換,使用指針的情況
源程序:
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<<"使用派生類指針調(diào)用函數(shù)"<<endl;
pDerived->Print();
pBase=pDerived;
cout<<"使用基類指針調(diào)用函數(shù)"<<endl;
pBase->Print();
//pBase->Func(); //錯(cuò)誤,通過(guò)基類指針不能調(diào)用派生類函數(shù)
//pDerived=pBase; //錯(cuò)誤,派生類指針=基類指針
pDerived=(CDerived*)pBase; //強(qiáng)制類型轉(zhuǎn)換,派生類指針=基類指針
cout<<"使用派生類指針調(diào)用函數(shù)"<<endl;
pDerived->Print();
return 0;
}
運(yùn)行結(jié)果:
總結(jié)
以上是生活随笔為你收集整理的自考新教材-p233的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 世界上最成功的10位Logo 设计师
- 下一篇: 整数集合