-->
当前位置:首页 > 题库 > 正文内容

Luz4年前 (2021-03-08)题库2768
6-4 派生类使用基类的成员函数 (10 分)

按要求完成下面的程序:
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
作者
李廷元
单位
民用航空飞行学院
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
class Animal{
	private:
		int m_nWeightBase;
	protected:
		int m_nAgeBase;
	public:
		void set_weight(int n)
		{
			m_nWeightBase=n;
		}
		void set_age(int m){
			m_nAgeBase=m;
		}
		int get_weight(){
			return m_nWeightBase;
		}
	
};
class Cat:public Animal{
	private:
		string m_strName;
	public:
		Cat(string a)
		{
			m_strName=a;
		}
		void print_age()
		{
			cout<<m_strName<<","<<" age = "<<m_nAgeBase<<endl;
		}
};