码迷,mamicode.com
首页 > 其他好文 > 详细

自考新教材-p238_1

时间:2020-02-04 21:58:22      阅读:69      评论:0      收藏:0      [点我收藏+]

标签:image   system   code   函数   public   protected   space   amp   protect   

源程序:

#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 << "使用派生类指针pDerived调用函数Print()" << endl;
pDerived->Print(); //调用的是派生类中的函数

cout << "使用基类指针pBase调用函数Print()" << endl;
pBase = pDerived;
pBase->Print(); //调用的是基类中的函数

cout << "使用派生类指针调用函数" << endl;
pDerived->Print(); //调用的是派生类中的函数
system("pause");
return 1;

}

运行结果:

技术图片

 

自考新教材-p238_1

标签:image   system   code   函数   public   protected   space   amp   protect   

原文地址:https://www.cnblogs.com/duanqibo/p/12261544.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!