贵州大学oj C++ 第五次 4.继承与虚函数之三

记录学习日常 代码可能有错 大家多多包涵 有好的建议提出的话 我会开心接纳 初学阶段 

有一个类Base及其公有派生类Derived1、Derived2、Derived3。类Base和main函数的代码已经完成,请根据已有的代码给出上述三个派生类的设计。(只需要提交这三个类的代码)

程序的开头部分如下:

#include <iostream>

using namespace std;

class Base{

    int x,y;

public:

    Base(int a,int b):x(a),y(b){}

    int getX()const{return x;}

    int getY()const{return y;}

    virtual void calculate()=0;

};

main函数的代码如下:

int main(){

    Base *p;

    Derived1 o1(1,2,3);

    Derived2 o2(4,5,6);

    Derived3 o3(7,8,9);

    p=&o1;

    p->calculate();

    p=&o2;

    p->calculate();

    p=&o3;

    p->calculate();

    return 0;

}

输出描述

三个数的和是6

三个数的积是120

前两个数的和与第三个数的积是135

class Derived1:public Base{
    int x,y,z;
public:
    Derived1()=default;
    Derived1(int x,int y,int z):x(x),y(y),z(z), Base(x,y){}
    void calculate(){
        cout<<"三个数的和是"<<x+y+z<<endl;
    }
};
class Derived2:public Base{
    int x,y,z;
public:
    Derived2()=default;
    Derived2(int x,int y,int z):x(x),y(y),z(z), Base(x,y){}
    void calculate(){
        cout<<"三个数的积是"<<x*y*z<<endl;
    }
};
class Derived3:public Base{
    int x,y,z;
public:
    Derived3()=default;
    Derived3(int x,int y,int z):x(x),y(y),z(z), Base(x,y){}
    void calculate(){
        cout<<"前两个数的和与第三个数的积是"<<(x+y)*z<<endl;
    }
};

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值