用c++类的组合技术,设计一个基本信息类、一个学生类、一个教师类。基本信息类包括姓名、性别、手机号、班级;学生类包括姓名、性别、手机号、班级、数学、语文和英语等成绩;教师类包括姓名、性别、手机号、班级、专业、教龄等。以上三个类必须包含构造函数,其他成员函数自行设计。主函数中,分别生成一个学生类和教师类对象,并调用成员函数。并分析
时间: 2023-10-20 21:38:26 浏览: 68
首先我们可以使用组合技术,将基本信息类作为学生类和教师类的成员变量。这样可以避免在学生类和教师类中重复定义姓名、性别、手机号和班级等基本信息。
以下是一个基本信息类的实现:
```cpp
class BasicInfo {
public:
BasicInfo(const string& name, const string& gender, const string& phone, const string& cls)
: name_(name), gender_(gender), phone_(phone), cls_(cls) {}
string getName() const { return name_; }
string getGender() const { return gender_; }
string getPhone() const { return phone_; }
string getCls() const { return cls_; }
private:
string name_;
string gender_;
string phone_;
string cls_;
};
```
接下来是学生类的实现:
```cpp
class Student {
public:
Student(const string& name, const string& gender, const string& phone, const string& cls,
double math, double chinese, double english)
: basicInfo_(name, gender, phone, cls), math_(math), chinese_(chinese), english_(english) {}
double getMath() const { return math_; }
double getChinese() const { return chinese_; }
double getEnglish() const { return english_; }
double getAverage() const { return (math_ + chinese_ + english_) / 3; }
void printInfo() const {
cout << "Name: " << basicInfo_.getName() << endl;
cout << "Gender: " << basicInfo_.getGender() << endl;
cout << "Phone: " << basicInfo_.getPhone() << endl;
cout << "Class: " << basicInfo_.getCls() << endl;
cout << "Math: " << math_ << endl;
cout << "Chinese: " << chinese_ << endl;
cout << "English: " << english_ << endl;
cout << "Average: " << getAverage() << endl;
}
private:
BasicInfo basicInfo_;
double math_;
double chinese_;
double english_;
};
```
最后是教师类的实现:
```cpp
class Teacher {
public:
Teacher(const string& name, const string& gender, const string& phone, const string& cls,
const string& major, int years)
: basicInfo_(name, gender, phone, cls), major_(major), years_(years) {}
string getMajor() const { return major_; }
int getYears() const { return years_; }
void printInfo() const {
cout << "Name: " << basicInfo_.getName() << endl;
cout << "Gender: " << basicInfo_.getGender() << endl;
cout << "Phone: " << basicInfo_.getPhone() << endl;
cout << "Class: " << basicInfo_.getCls() << endl;
cout << "Major: " << major_ << endl;
cout << "Years: " << years_ << endl;
}
private:
BasicInfo basicInfo_;
string major_;
int years_;
};
```
在主函数中,我们可以分别生成一个学生类和教师类对象,并调用成员函数进行输出:
```cpp
int main() {
Student s("Tom", "Male", "123456789", "Grade 1, Class 1", 80, 90, 85);
s.printInfo();
Teacher t("Lucy", "Female", "987654321", "Grade 1, Class 2", "Math", 3);
t.printInfo();
return 0;
}
```
输出结果如下:
```
Name: Tom
Gender: Male
Phone: 123456789
Class: Grade 1, Class 1
Math: 80
Chinese: 90
English: 85
Average: 85
Name: Lucy
Gender: Female
Phone: 987654321
Class: Grade 1, Class 2
Major: Math
Years: 3
```
从输出结果可以看出,我们成功地使用了组合技术,将基本信息类作为学生类和教师类的成员变量,避免了重复定义基本信息。同时,我们也成功地实现了构造函数和其他成员函数,并在主函数中调用了这些函数,输出了学生和教师的基本信息和成绩或教龄等信息。
阅读全文