派生类使用基类的成员函数 (15 分)

派生类使用基类的成员函数 (15 分)
按要求完成下面的程序:
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;
class Animal
{
protected:
    int m_nWeightBase;//表示Animal的体重
    int m_nAgeBase;//表示Animal的年龄
public:
    Animal(int m_nWeightBase=0,int m_nAgeBase=0)
    {
        this->m_nWeightBase = m_nWeightBase;
        this->m_nAgeBase = m_nAgeBase;
    }
    void set_weight(int nWeightBase)//初始化数据成员nWeightBase
    {
        this->m_nWeightBase = nWeightBase;
    }
    int get_weight()//返回数据成员nWeightBase的值
    {
        return m_nWeightBase;
    }
    void set_age(int age)
    {
        this->m_nAgeBase = age;
    }
};
class Cat: public Animal
{
private:
    string m_strName;
public:
    Cat(string name)
    {
        this->m_strName = name;
    }
    Cat(int m_nWeightBase, int m_nAgeBase, string m_strName) :Animal(m_nWeightBase, m_nAgeBase)
    {
        this->m_strName = m_strName;
    }
    void print_age()
    {
        cout << this->m_strName << ", age = " << this->m_nAgeBase << endl;
    }
};

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;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值