私有继承派生类使用基类的成员函数

按要求完成下面的程序:

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

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

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

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

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

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

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

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

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

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

(4)公有的成员函数set_print_weight,功能是首先调用基类的成员函数set_weight设置数据成员nWeightBase的值为6,接着输出成员m_strName的值,然后输出“, weight = ”,最后调用基类的成员函数get_weight输出基类的数据成员m_nAgeBase的值。具体输出格式参见main函数和样例输出。

类和函数接口定义:

 
参见题目描述。
 

裁判测试程序样例:

 
#include <iostream>
#include <string>
using namespace std;

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

int main()
{
    Cat cat("Persian");     //定义派生类对象cat
    cat.set_print_age();
    cat.set_print_weight(); //派生类对象调用自己的公有函数
    return 0;
}

 

输入样例:

本题无输入。

输出样例:

Persian, age = 5
Persian, weight = 6
复制代码
 1 class Animal{
 2   private:
 3     int m_nWeightBase;  
 4   protected:
 5     int m_nAgeBase;
 6    public:
 7   void set_weight(int a){
 8 m_nWeightBase=a;
 9     }
10   int get_weight(){
11        return m_nWeightBase ;
12     }
13 void set_age(int b)
14 {
15     m_nAgeBase=b; 
16 }
17 };
18 class Cat : private Animal{
19     private:
20     string m_strName;
21    public:   
22     using Animal::set_age;
23     using Animal::set_weight;
24     Cat(string c):m_strName(c){};
25     void set_print_age(){
26         set_age(5);
27         cout<<m_strName<<", age = "<<Animal::m_nAgeBase<<endl;
28         
29     }
30   void set_print_weight(){
31       set_weight(6);
32         cout<<m_strName<<", weight = "<<get_weight()<<endl;
33     }
34 };
复制代码

 

posted @   刘冰宇  阅读(161)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
点击右上角即可分享
微信分享提示