一、问题描述。
用对象和指针来观察基类与派生类中成员函数的调用。
二、设计思路。
1、定义一个拥有fn1,fn2两个成员函数的基类BaseClass
2、由基类BaseClass派生出一个同样拥有fn1,fn2两个成员函数的派生类DerivedClass
3、在主函数中声明一个派生类的对象,及基类与派生类的指针
4、观察运行结果
三、程序流程图
四、代码实现。
#pragma once
#include<iostream>
using namespace std;
class BaseClass
{
public:
BaseClass();
~BaseClass();
void fn1();
void fn2();
};
#include "BaseClass.h"
BaseClass::BaseClass()
{
}
BaseClass::~BaseClass()
{
}
void BaseClass::fn1()
{
cout << "base.fn1()" << endl;
}
void BaseClass::fn2()
{
cout << "base.fn2()" << endl;
}
#pragma once
#include"BaseClass.h"
class DerivedClass:public BaseClass
{
public:
DerivedClass();
~DerivedClass();
void fn1();
void fn2();
};
#include "DerivedClass.h"
DerivedClass::DerivedClass()
{
}
DerivedClass::~DerivedClass()
{
}
void DerivedClass::fn1()
{
cout << "Derived.fn1()" << endl;
}
void DerivedClass::fn2()
{
cout << "Derived.fn2()" << endl;
}
#include<iostream>
#include "DerivedClass.h"
using namespace std;
int main()
{
DerivedClass a;
BaseClass b;
DerivedClass c;
BaseClass *pb=&b;
DerivedClass *pd=&c;
cout << "用对象调用" << endl;
a.fn1(); a.fn2();
cout << "用BaseClass指针调用" << endl;
pb->fn1(); pb->fn2();
cout << "用DerivedClass指针调用" << endl;
pd->fn1(); pd->fn2();
}
标签:调用,fn2,fn1,void,基类,DerivedClass,派生类,BaseClass,cout From: https://www.cnblogs.com/luoqingci/p/17316328.html