欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 综合教程 >内容正文

综合教程

自考新教材-p233

发布时间:2024/6/21 综合教程 56 生活家
生活随笔 收集整理的这篇文章主要介绍了 自考新教材-p233 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

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

源程序:

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的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。