[C++/PTA] 派生类使用基类的成员函数

[C++/PTA] 派生类使用基类的成员函数

题目要求

按要求完成下面的程序:

1、定义一个Animal类,成员包括:

(1)整数类型的私有数据成员m_nWeightBase,表示Animal的体重;

(2)整数类型的保护数据成员m_nAgeBase,表示Animal的年龄;

(3)公有函数成员set_weight,用指定形参初始化数据成员nWeightBase;

(4)公有成员函数get_weight,返回数据成员nWeightBase的值;

(5)公有函数成员set_age,用指定形参初始化数据成员m_nAgeBase;

2、定义一个Cat类,公有继承自Animal类,其成员包括:

(1)string类型的私有数据成员m_strName;

(2)带参数的构造函数,用指定形参对私有数据成员进行初始化;

(3)公有的成员函数print_age,功能是首先输出成员m_strName的值,然后输出“, age = ”,接着输出基类的数据成员m_nAgeBase的值。具体输出格式参见main函数和样例输出。

类和函数接口定义:
参见题目描述。

裁判测试程序样例:

#include <iostream>

#include <string>

using namespace std;


/* 请在这里填写答案 */


int main()

{
    
    

    Cat cat("Persian");   //定义派生类对象cat

    cat.set_age(5);       //派生类对象调用从基类继承的公有成员函数

    cat.set_weight(6);    //派生类对象调用从基类继承的公有成员函数

    cat.print_age();      //派生类对象调用自己的公有函数

    cout << "cat weight = " << cat.get_weight() << endl;

    return 0;

}

输入样例:
本题无输入。

输出样例:
Persian, age = 5
cat weight = 6

解题思路

定义Animal类,包括私有成员变量m_nWeightBase表示体重,
保护成员变量m_nAgeBase表示年龄以及一些操作这些成员变量的函数。

定义Cat类,公有继承自Animal类,包括私有成员变量m_strName表示名字,
带参数的构造函数,用指定参数初始化名字,以及print_age函数,输出Cat的名字和年龄。

代码

class Animal
{
    
    
public:
    Animal() {
    
    }; // 默认构造函数

private:
    int m_nWeightBase; // Animal的体重作为私有成员变量
protected:
    int m_nAgeBase; // Animal的年龄作为保护成员变量,可以被派生类直接访问
public:
    void set_weight(int a)
    {
    
    
        this->m_nWeightBase=a; // 用指定参数a初始化Animal的体重
    }
    int get_weight()
    {
    
    
        return m_nWeightBase; // 返回Animal的体重
    }
    void set_age(int a)
    {
    
    
        this->m_nAgeBase = a; // 用指定参数a初始化Animal的年龄
    }
    int get_age()
    {
    
    
        return m_nAgeBase; // 返回Animal的年龄
    }
};

class Cat :public Animal // 公有继承自Animal类
{
    
    
private:
    string m_strName; // Cat独有的私有成员变量名字
    int age; // 不需要维护的私有成员变量年龄,因为Cat继承了Animal的年龄变量m_nAgeBase

public:
    Cat() {
    
     }; // 默认构造函数

    Cat(string name) // 带参数的构造函数,用指定参数初始化Cat的名字
    {
    
    
        this->m_strName = name;
    }

    void print_age()
    {
    
    
        cout << m_strName << ", age = " << m_nAgeBase << endl; 
        // 输出Cat的名字和继承自Animal类的年龄
    }
};

总结

该题结合基类考察派生类的基本知识,读者可躬身实践。
我是秋说,我们下次见。

猜你喜欢

转载自blog.csdn.net/2301_77485708/article/details/130954437