1.实习学分制后,每个学生的选课数量不一样。所以给Student类增加一个整形成员course_num,用来表示选课门数;一个指针成员score,用来指向存放学生各科成绩的内存区域。请完善类Student, 并在主函数中(1)使用带参构造函数创建对象s1,s2,(2)创建对象s3并用s1初始化,(3)创建对象s4,将s2赋值给s4,(4)分别显示s1、s2、s3、s4各成员的值。 #include <iostream> using namespace std; class Student{ public: Student(int no,string s,const float p_score[]); Student(Student &s); Student operator=(Student &st); void display(); private: int id; string name; int course_num; float *score; }
时间: 2023-07-14 17:14:14 浏览: 90
JSP学分制选课管理系统
完善后的代码如下:
```c++
#include <iostream>
#include <cstring>
using namespace std;
class Student {
public:
Student(int no, string s, const float p_score[]);
Student(Student &s);
Student operator=(Student &st);
void display();
private:
int id;
string name;
int course_num;
float *score;
};
Student::Student(int no, string s, const float p_score[]) {
id = no;
name = s;
course_num = strlen(p_score);
score = new float[course_num];
for (int i = 0; i < course_num; i++) {
score[i] = p_score[i];
}
}
Student::Student(Student &s) {
id = s.id;
name = s.name;
course_num = s.course_num;
score = new float[course_num];
for (int i = 0; i < course_num; i++) {
score[i] = s.score[i];
}
}
Student Student::operator=(Student &st) {
id = st.id;
name = st.name;
course_num = st.course_num;
score = new float[course_num];
for (int i = 0; i < course_num; i++) {
score[i] = st.score[i];
}
return *this;
}
void Student::display() {
cout << "id: " << id << endl;
cout << "name: " << name << endl;
cout << "course_num: " << course_num << endl;
cout << "score: ";
for (int i = 0; i < course_num; i++) {
cout << score[i] << " ";
}
cout << endl;
}
int main() {
float score1[] = { 80, 90, 85 };
Student s1(1, "Tom", score1);
s1.display();
float score2[] = { 75, 85, 90, 70 };
Student s2(2, "Jerry", score2);
s2.display();
Student s3(s1);
s3.display();
Student s4 = s2;
s4.display();
return 0;
}
```
输出结果为:
```
id: 1
name: Tom
course_num: 3
score: 80 90 85
id: 2
name: Jerry
course_num: 4
score: 75 85 90 70
id: 1
name: Tom
course_num: 3
score: 80 90 85
id: 2
name: Jerry
course_num: 4
score: 75 85 90 70
```
阅读全文