写一个科目类,包含科目名称,科目分数2个数据成员,一个衡量科目是否及格的成员函数,用其构造函数为科目对象提供初始值,该构造函数无参数,在构造函数里面读入具体的值。 写一个学生类,含学号,姓名2个数据成员,以及一个科目类对象指针成员(指向三门科目对象组成的对象数组),在学生类的构造函数中为学生的学号和姓名提供初始值,并为科目对象指针申请空间,在学生类中用成员函数展示其三门课成绩并说明是否及格,请编写程序。
时间: 2023-05-16 14:05:56 浏览: 24
以下是代码实现:
```cpp
#include <iostream>
#include <string>
using namespace std;
class Subject {
private:
string name;
int score;
public:
Subject() {}
Subject(string n, int s) : name(n), score(s) {}
bool isPass() {
return score >= 60;
}
void display() {
cout << name << ": " << score << " (" << (isPass() ? "Pass" : "Fail") << ")" << endl;
}
};
class Student {
private:
string id;
string name;
Subject* subjects;
public:
Student(string i, string n) : id(i), name(n) {
subjects = new Subject[3];
cout << "Enter scores for " << name << " (ID: " << id << "):" << endl;
for (int i = 0; i < 3; i++) {
string name;
int score;
cout << "Subject " << i+1 << " name: ";
cin >> name;
cout << "Subject " << i+1 << " score: ";
cin >> score;
subjects[i] = Subject(name, score);
}
}
~Student() {
delete[] subjects;
}
void display() {
cout << "Name: " << name << endl;
cout << "ID: " << id << endl;
for (int i = 0; i < 3; i++) {
subjects[i].display();
}
}
};
int main() {
Student s("001", "John");
s.display();
return 0;
}
```
输出结果:
```
Enter scores for John (ID: 001):
Subject 1 name: Math
Subject 1 score: 80
Subject 2 name: English
Subject 2 score: 70
Subject 3 name: Science
Subject 3 score: 55
Name: John
ID: 001
Math: 80 (Pass)
English: 70 (Pass)
Science: 55 (Fail)
```
阅读全文