自考新教材-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;

}

运行结果:

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