实验7. 继承(一)
6-1 派生类使用基类的成员函数 (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
#include
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
class Animal {
private:
int m_nWeightBase;//LHL
protected:
int m_nAgeBase;
public:
void set_weight(int w) {
m_nWeightBase = w;
}
int get_weight() {
return m_nWeightBase; }
void set_age(int a) {
m_nAgeBase = a;
}
};
class Cat :private Animal {
//私有继承
private:
string m_strName;//LHL
public:
Cat(string name) {
m_strName = name;
}
void set_print_age() {
//LHL
set_age(5);
cout << m_strName <<", age = " << m_nAgeBase<<endl;
}
void set_print_weight() {
set_weight(6);
cout << m_strName << ", weight = " << get_weight() << endl;
}
};
6-2 汽车类的继承 (15分)
根据给定的汽车类vehicle(包含的数据成员有车轮个数wheels和车重weight)声明,完成其中成员函数的定义,之后再定义其派生类并完成测试。
小车类car是它的派生类,其中包含载人数passenger_load。每个类都有相关数据的输出方法。
Vehicle类声明如下:
#include
using namespace std;
class Vehicle
{
protected:
int wheels;
float weight;
public:
Vehicle(int wheels,float weight);
int get_wheels();
float get_weight();
float wheel_load();
void show();
};
/* 请在这里填写答案 */
裁判测试程序样例:
int main ()
{
Vehicle v(4,1000);
v.show();
Car car1(4,2000,5);
car1.show ();
return 0;
}
输出样例:
在这里给出相应的输出。例如:
Type:Vehicle
Wheel:4
Weight:1000kg
Type:Car
Type:Vehicle
Wheel:4
Weight:2000kg
Load:5 persons
https://wenku.baidu.com/view/1ec268cbd5bbfd0a79567308.html
-1 公有继承中派生类Student对基类Person成员的访问 (20分)
题目内容: 已知基类Person的定义如下:
class Person
{
string Name;
char Sex;
int Age;
public:
void Register(string name, int age, char sex)
{
Name=name;
Age=age;
Sex=sex;
}
void ShowMe() { cout<<Name<<" “<<Age<<” "<<Sex<<endl; }
};
请通过继承的方法建立一个派生类Student,其中
1.新增的数据成员有:
int Number; //学号
string ClassName; //班级
2.新增的成员函数有:
void RegisterStu(string classname, int number, string name, int age, char sex) //对数据成员赋值,并使用基类的Register
void ShowStu() //显示数据成员信息,并使用基类的ShowMe
在主程序中建立一个派生类对象,利用已有的成员函数分别显示派生类对象和基类对象的数据成员。
输入格式:
学生的班级、学号、姓名、年龄和性别
输出格式:
先输出派生类对象的数据成员,依次为 学号、班级、姓名、年龄和性别
再输出基类的数据成员,依次为姓名、年龄和性别
输入样例:
在这里给出一组输入。例如:
18软件班 180001 李木子 18 m
输出样例:
在这里给出相应的输出。例如:
180001 18软件班 李木子 18 m
李木子 18 m
#include<iostream>
#include <cstring>//
C++编程:继承与派生类实现及应用

该博客主要介绍了C++编程中的继承概念,包括Animal、Cat类的定义与使用,展示了如何通过公有继承实现成员函数的调用。此外,还涉及了Vehicle、Car类的继承,以及Student类对Person类的公有继承,解释了如何添加新的数据成员和成员函数。最后,讲解了Point和Circle类的继承关系,实现计算圆周长的功能,并给出了不同维度点类的继承实现及其距离计算方法。
最低0.47元/天 解锁文章
4899

被折叠的 条评论
为什么被折叠?



