C++完成两个子类的构建,基类已给出

已经完成了基类Sport,现在需要接着完成子类SportRun和子类SportBicycle。

回忆在学习面向对象编程时“继承”和“多态”是两个非常重要的概念,也是这两个概念让代码的复用变得非常方便,我的基类是按照如下方法定义的:

class Sport{
protected:
int minutes, level;
public:
Sport(int minutes, int level):
minutes(minutes),
level(level){
}
virtual string getDescription() = 0;
virtual int getSportIntensity() = 0;
};

可以发现两个函数被定义为了纯虚函数,需要实现两个端口。

在主程序中,仅需要
Sport *sp = new Sportxxx();
sp -> getDescription();

即可轻松实现函数的运行期绑定。

下面对两个子类进行说明:

Part 1. class SportRun
getDescrption 将返回一个字符串,表示对于运动过程的描述。
返回格式:    You're running for %d minute(s)
其中%d表示SportRun实例在构造时传入的分钟数。

getSportIntensity 将返回一个整数,表示通过该运动获得的“活力值”
跑步运动的“活力值”计算方式为:
[minutes/10]×level
其中中括号表示取整。

Part 2. class SportBicycle
getDescrption 将返回一个字符串,表示对于运动过程的描述。
返回格式:    You're riding for %d minute(s)
其中%d表示SportBicycle实例在构造时传入的分钟数。

getSportIntensity 将返回一个整数,表示通过该运动获得的“活力值”
跑步运动的“活力值”计算方式为:
[minutes/5]^2×level
下面是已经写好的框架
class SportRun: public Sport{
public:
SportRun(int m, int l): Sport(m, l){}
};

class SportBicycle: public Sport{
public:
SportBicycle(int m, int l): Sport(m, l){}
};

望采纳

已经帮你完成满足需求的C++代码(带注释)如下:

#include <iostream>
#include <string>

using namespace std;

// 定义基类Sport
class Sport {
protected:
    int minutes; // 运动时间,单位为分钟
    int level;   // 运动强度

public:
    // 定义构造函数
    Sport(int minutes, int level) : minutes(minutes), level(level) {}

    // 定义虚函数getDescription,用来描述运动过程
    virtual string getDescription() = 0;

    // 定义虚函数getSportIntensity,用来计算运动强度
    virtual int getSportIntensity() = 0;
};

// 定义子类SportRun,继承自Sport
class SportRun : public Sport {
public:
    // 定义构造函数,并调用基类的构造函数
    SportRun(int m, int l) : Sport(m, l) {}

    // 实现虚函数getDescription
    string getDescription() {
        // 返回描述运动过程的字符串
        return "You're running for " + to_string(minutes) + " minute(s).";
    }

    // 实现虚函数getSportIntensity
    int getSportIntensity() {
        // 计算运动强度
        return (minutes / 10) * level;
    }
};

// 定义子类SportBicycle,继承自Sport
class SportBicycle : public Sport {
public:
    // 定义构造函数,并调用基类的构造函数
    SportBicycle(int m, int l) : Sport(m, l) {}

    // 实现虚函数getDescription
    string getDescription() {
        // 返回描述运动过程的字符串
        return "You're riding for " + to_string(minutes) + " minute(s).";
    }

    // 实现虚函数getSportIntensity
    int getSportIntensity() {
        // 计算运动强度
        return (minutes / 5) * (minutes / 5) * level;
    }
};

int main() {
    // 定义一个Sport指针,指向SportRun的实例
    Sport *sp = new SportRun(30, 3);
    // 调用getDescription函数
    cout << sp->getDescription() << endl;
    // 调用getSportIntensity函数
    cout << sp->getSportIntensity() << endl;

    // 定义一个Sport指针,指向SportBicycle的实例
    sp = new SportBicycle(20, 2);
    // 调用getDescription函数
    cout << sp->getDescription() << endl;
    // 调用getSportIntensity函数
    cout << sp->getSportIntensity() << endl;

    return 0;
}

已经自己写出来了🥰