C++用类的组合技术,设计一个基本信息类、一个学生类、一个教师类。基本信息类包括姓名、性别、手机号、班级;学生类包括姓名、性别、手机号、班级、数学、语文和英语等成绩;教师类包括姓名、性别、手机号、班级、专业、教龄等。以上三个类必须包含构造函数,其他成员函数自行设计。主函数中,分别生成一个学生类和教师类对象,并调用成员函数
时间: 2023-10-14 14:06:11 浏览: 39
好的,以下是C++代码示例:
```cpp
#include<iostream>
#include<string>
using namespace std;
class BasicInfo {
public:
BasicInfo(string name, string gender, string phone_num, string class_num) {
this->name = name;
this->gender = gender;
this->phone_num = phone_num;
this->class_num = class_num;
}
string name;
string gender;
string phone_num;
string class_num;
};
class Student {
public:
Student(string name, string gender, string phone_num, string class_num, int math, int chinese, int english) {
this->basic_info = BasicInfo(name, gender, phone_num, class_num);
this->math = math;
this->chinese = chinese;
this->english = english;
}
BasicInfo basic_info;
int math;
int chinese;
int english;
int get_total_score() {
return math + chinese + english;
}
};
class Teacher {
public:
Teacher(string name, string gender, string phone_num, string class_num, string major, int teaching_years) {
this->basic_info = BasicInfo(name, gender, phone_num, class_num);
this->major = major;
this->teaching_years = teaching_years;
}
BasicInfo basic_info;
string major;
int teaching_years;
string get_teaching_experience() {
return basic_info.name + " has " + to_string(teaching_years) + " years of teaching experience in " + major + ".";
}
};
int main() {
// 创建一个学生对象
Student student("小明", "男", "123456789", "一班", 90, 85, 92);
cout << student.basic_info.name << "的总成绩是" << student.get_total_score() << "分。" << endl;
// 创建一个教师对象
Teacher teacher("张老师", "女", "987654321", "二班", "英语", 10);
cout << teacher.get_teaching_experience() << endl;
return 0;
}
```
输出结果如下:
```
小明的总成绩是267分。
张老师 has 10 years of teaching experience in 英语.
```
在上述代码中,我们使用了类的组合技术,将基本信息类作为学生类和教师类的成员变量,这样可以避免代码冗余并提高代码复用性。同时,我们也为每个类设计了构造函数,并添加了一些自定义的成员函数,以满足不同的需求。在主函数中,我们分别创建了一个学生对象和一个教师对象,并调用了它们的成员函数。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)