2. 创建工程Test2,新建teacher.h文件和teacher.cpp文件。具体要求如下:定义学生类,其中至少包括姓名、性别、学号和成绩。实现如下功能:
(1)姓名、性别、学号、成绩的初始化采用有参构造函数和无参构造函数2类方法。
(2)输入所有同学的成绩;
(3)求不及格的人数;
(4)求该所有同学成绩的平均分;
```c++
#ifndef TEACHER_H
#define TEACHER_H
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Student {
public:
Student();
Student(string name, string gender, string id, float score);
void inputScores();
int countFailed();
float getAverageScore();
private:
string name;
string gender;
string id;
float score;
vector<float> scores;
};
#endif
#include "teacher.h"
Student::Student() {}
Student::Student(string name, string gender, string id, float score) {
this->name = name;
this->gender = gender;
this->id = id;
this->score = score;
}
void Student::inputScores() {
int n;
cout << "请输入学生人数: ";
cin >> n;
for (int i = 0; i < n; i++) {
float score;
cout << "请输入第" << i + 1 << "个学生的成绩: ";
cin >> score;
scores.push_back(score);
}
}
int Student::countFailed() {
int cnt = 0;
for (float score : scores) {
if (score < 60) {
cnt++;
}
}
return cnt;
}
float Student::getAverageScore() {
float sum = score;
for (float s : scores) {
sum += s;
}
return sum / (scores.size() + 1);
}
#include "teacher.h"
int main() {
Student stu("张三", "男", "1001", 90);
stu.inputScores();
cout << "不及格的人数:" << stu.countFailed() << endl;
cout << "平均分:" << stu.getAverageScore() << endl;
return 0;
}
```c++