2.创建student类,在main函数中输入3个学生数据,包括学号,姓名和成绩,要求只输出成绩在80~90分数段的学生数据。 具体要求如下: (1)数据成员设定成private (2)成员函数设定成public (3)将类声明和成员函数的定义分开,放到.h和.cpp中
时间: 2024-01-02 18:03:24 浏览: 82
student.h文件:
```c++
#ifndef STUDENT_H
#define STUDENT_H
#include <string>
class Student {
private:
std::string id; // 学号
std::string name; // 姓名
int score; // 成绩
public:
Student(const std::string& id, const std::string& name, int score);
std::string getId() const;
std::string getName() const;
int getScore() const;
};
#endif // STUDENT_H
```
student.cpp文件:
```c++
#include "student.h"
Student::Student(const std::string& id, const std::string& name, int score) : id(id), name(name), score(score) {}
std::string Student::getId() const {
return id;
}
std::string Student::getName() const {
return name;
}
int Student::getScore() const {
return score;
}
```
main.cpp文件:
```c++
#include <iostream>
#include "student.h"
int main() {
Student students[] = {
Student("001", "Tom", 85),
Student("002", "Jerry", 90),
Student("003", "Mike", 75)
};
for (const auto& student : students) {
int score = student.getScore();
if (score >= 80 && score <= 90) {
std::cout << "id: " << student.getId() << ", name: " << student.getName() << ", score: " << score << std::endl;
}
}
return 0;
}
```
阅读全文