自考新教材-p238_1

源程序:

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

}

运行结果:

 

posted @ 2020-02-04 21:30  bobo哥  阅读(197)  评论(0编辑  收藏  举报