用类的组合技术,设计一个基本信息类、一个学生类、一个教师类。基本信息类包括姓名、性别、手机号、班级;学生类包括姓名、性别、手机号、班级、数学、语文和英语等成绩;教师类包括姓名、性别、手机号、班级、专业、教龄等。以上三个类必须包含构造函数,其他成员函数自行设计。主函数中,分别生成一个学生类和教师类对象,并调用成员函数。
时间: 2023-10-20 09:38:04 浏览: 63
好的,这里是您所需要的代码:
```c++
#include <iostream>
#include <string>
using namespace std;
class BasicInfo {
private:
string name;
string gender;
string phone;
string clazz;
public:
BasicInfo(string n, string g, string p, string c) {
name = n;
gender = g;
phone = p;
clazz = c;
}
void display() {
cout << "Name: " << name << endl;
cout << "Gender: " << gender << endl;
cout << "Phone: " << phone << endl;
cout << "Class: " << clazz << endl;
}
};
class Student {
private:
BasicInfo info;
float math;
float chinese;
float english;
public:
Student(string n, string g, string p, string c, float m, float ch, float e) : info(n, g, p, c) {
math = m;
chinese = ch;
english = e;
}
void display() {
info.display();
cout << "Math: " << math << endl;
cout << "Chinese: " << chinese << endl;
cout << "English: " << english << endl;
}
};
class Teacher {
private:
BasicInfo info;
string major;
int experience;
public:
Teacher(string n, string g, string p, string c, string m, int exp) : info(n, g, p, c) {
major = m;
experience = exp;
}
void display() {
info.display();
cout << "Major: " << major << endl;
cout << "Experience: " << experience << " years" << endl;
}
};
int main() {
Student s("Tom", "Male", "123456789", "Class1", 90, 80, 70);
s.display();
cout << endl;
Teacher t("Jerry", "Male", "987654321", "Class2", "Math", 5);
t.display();
return 0;
}
```
运行结果:
```
Name: Tom
Gender: Male
Phone: 123456789
Class: Class1
Math: 90
Chinese: 80
English: 70
Name: Jerry
Gender: Male
Phone: 987654321
Class: Class2
Major: Math
Experience: 5 years
```
在这个程序中,我们使用了类的组合技术,将基本信息类作为学生类和教师类的成员变量。这样一来,我们就可以通过基本信息类的构造函数来初始化学生类和教师类的姓名、性别、手机号和班级这些成员变量。在学生类中,我们还添加了数学、语文和英语三个成员变量,用来存储学生的成绩。在教师类中,我们添加了专业和教龄两个成员变量,用来描述教师的专业和从教年限。最后,在主函数中,我们分别生成了一个学生类对象和一个教师类对象,并调用了它们的成员函数输出信息。
阅读全文