定义一个基类有姓名、性别、年龄,再由基类派生出教师类和学生类。教师类增加工号、职称和工资,学生类增加学号、班级、专业和入学成绩。编程要求:1、设计虚函数输出教师和学生的基本信息;2、计算教师的平均工资并输出;3、使用友元函数重载运算符“<”,找出入学成绩最高的学生并输出;
时间: 2024-01-24 11:03:38 浏览: 23
好的,这是一个经典的面向对象编程问题。以下是实现该问题的C++代码:
```c++
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Person {
public:
Person(string name, string gender, int age) : name_(name), gender_(gender), age_(age) {}
virtual void PrintInfo() {
cout << "Name: " << name_ << endl;
cout << "Gender: " << gender_ << endl;
cout << "Age: " << age_ << endl;
}
protected:
string name_;
string gender_;
int age_;
};
class Teacher : public Person {
public:
Teacher(string name, string gender, int age, int id, string title, double salary)
: Person(name, gender, age), id_(id), title_(title), salary_(salary) {}
virtual void PrintInfo() {
Person::PrintInfo();
cout << "ID: " << id_ << endl;
cout << "Title: " << title_ << endl;
cout << "Salary: " << salary_ << endl;
}
static double GetAvgSalary(vector<Teacher> teachers) {
double total_salary = 0;
for (auto teacher : teachers) {
total_salary += teacher.salary_;
}
return total_salary / teachers.size();
}
private:
int id_;
string title_;
double salary_;
};
class Student : public Person {
public:
friend bool operator<(const Student& s1, const Student& s2);
Student(string name, string gender, int age, int id, string cls, string major, double score)
: Person(name, gender, age), id_(id), cls_(cls), major_(major), score_(score) {}
virtual void PrintInfo() {
Person::PrintInfo();
cout << "ID: " << id_ << endl;
cout << "Class: " << cls_ << endl;
cout << "Major: " << major_ << endl;
cout << "Score: " << score_ << endl;
}
private:
int id_;
string cls_;
string major_;
double score_;
};
bool operator<(const Student& s1, const Student& s2) {
return s1.score_ < s2.score_;
}
int main() {
Teacher t1("Tom", "Male", 35, 1001, "Associate Professor", 8000);
Teacher t2("Mary", "Female", 40, 1002, "Professor", 10000);
vector<Teacher> teachers = {t1, t2};
cout << "The average salary of teachers is: " << Teacher::GetAvgSalary(teachers) << endl;
Student s1("Jack", "Male", 18, 2001, "Class 1", "Computer Science", 90);
Student s2("Lucy", "Female", 19, 2002, "Class 2", "English", 95);
if (s1 < s2) {
cout << "The student with the highest score is: " << endl;
s2.PrintInfo();
} else {
cout << "The student with the highest score is: " << endl;
s1.PrintInfo();
}
return 0;
}
```
以上代码中,我们定义了一个`Person`类作为基类,包含了姓名、性别、年龄三个基本属性,并定义了一个`virtual`虚函数`PrintInfo`,用于输出个人信息。然后定义了两个派生类`Teacher`和`Student`,分别表示教师和学生。教师类增加了工号、职称和工资三个属性,并实现了`PrintInfo`函数和一个静态函数`GetAvgSalary`,用于计算教师的平均工资。学生类增加了学号、班级、专业和入学成绩四个属性,并实现了`PrintInfo`函数。为了找出入学成绩最高的学生,我们使用了一个友元函数`operator<`,用于重载小于运算符,比较两个学生的成绩大小。在`main`函数中,我们分别创建了两个教师对象和两个学生对象,并使用了上述定义的函数和运算符,输出了相关信息。
注意,该代码仅供参考,实际应用中可能还需要进行更完善的设计和实现。