【派生对象和基类对象指针的使用(类型兼容性规则)】

创建了一个基类BaseClass和派生类DerivedClass,基类和派生类都有fn1()和fn2()函数。通过DerivedClass对象、BaseClass指针和DerivedClass指针调用这些函数,展示C++中的多态性和类型兼容性原则。
摘要由CSDN通过智能技术生成

【问题描述】声明-个基类BaseClass,从它派生出类DerivedClass,BaseClass有成员2数fnl()、fn2(),DerivedClass也有成员函数fnl()、fn2(),在主函数中声明向DerivedClass的对象,分别用DerivedClass的对象以及BaseClass和DerivedClass的指针来调用fnl()、fn2(),观察运行结果。

【输入形式】无输入。

【输出形式】分别输出调用指定函数之后的指定信息。

【样例输入】无输入

【样例输出】

the fn1 founction of the DerivedClass

the fn2 founction of the DerivedClass

the fn1 founction of the baseclass

the fn2 founction of the baseclass

the fn1 founction of the DerivedClass

the fn2 founction of the DerivedClass

【程序说明】各个函数的实现中,只需要有相应的函数调用输出信息就可以了。

主函数中函数调用的依次为:DerivedClass对象调用函数fnl()、fn2();BaseClass类型指针指向DerivedClass对象调用函数fnl()、fn2();DerivedClass类型指针指向DerivedClass对象调用fnl()、fn2();

需要仔细观察调用的输出信息,理解类型兼容性原则和指向对象的指针。

代码如下:

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<string>
#include<istream>
#include<iomanip>
#include<ostream>
#include<list>
#include<vector>
#include<set>
#include<map>
#include<fstream>
#include<stack>
#include<ctime>
#include<deque>
#include<queue>
#include <sstream>
#include <numeric>
#pragma warning (disable:4996)

using namespace std;

class BaseClass {
public:
    void fn1() { cout << "the fn1 founction of the baseclass" << endl; }
    void fn2() { cout << "the fn2 founction of the baseclass" << endl; }
};

class DerivedClass : public BaseClass {
public:
    void fn1() { cout << "the fn1 founction of the DerivedClass" << endl; }
    void fn2() { cout << "the fn2 founction of the DerivedClass" << endl; }
};

int main() {
    DerivedClass obj;
    obj.fn1();
    obj.fn2();

    BaseClass* p1 = &obj;
    p1->fn1();
    p1->fn2();

    DerivedClass* p2 = &obj;
    p2->fn1();
    p2->fn2();

    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

武帝为此

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值