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-06-27 16:06:35 浏览: 101
CourseSelect.rar_CourseSelect学生选课系统_vs2010+SQL_选课_选课系统
首先需要在类的定义中增加新成员变量和构造函数、析构函数等。代码如下:
```cpp
#include <iostream>
#include <cstring>
using namespace std;
class Student {
public:
Student(int no, string s, const float p_score[], int c_num);
Student(Student &s);
~Student();
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[], int c_num) {
id = no;
name = s;
course_num = c_num;
score = new float[course_num];
memcpy(score, p_score, course_num * sizeof(float));
}
Student::Student(Student &s) {
id = s.id;
name = s.name;
course_num = s.course_num;
score = new float[course_num];
memcpy(score, s.score, course_num * sizeof(float));
}
Student::~Student() {
if (score != NULL) {
delete[] score;
}
}
Student Student::operator=(Student &st) {
if (this != &st) {
id = st.id;
name = st.name;
course_num = st.course_num;
if (score != NULL) {
delete[] score;
}
score = new float[course_num];
memcpy(score, st.score, course_num * sizeof(float));
}
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;
}
```
接下来在主函数中使用类的方法创建对象并初始化。代码如下:
```cpp
int main() {
float score1[] = {80, 90, 70};
Student s1(1001, "Tom", score1, 3);
s1.display();
float score2[] = {85, 95, 75, 80};
Student s2(1002, "Jerry", score2, 4);
s2.display();
Student s3(s1);
s3.display();
Student s4 = s2;
s4.display();
return 0;
}
```
执行程序后,输出结果如下:
```
id: 1001
name: Tom
course_num: 3
score: 80 90 70
id: 1002
name: Jerry
course_num: 4
score: 85 95 75 80
id: 1001
name: Tom
course_num: 3
score: 80 90 70
id: 1002
name: Jerry
course_num: 4
score: 85 95 75 80
```
可以看到,程序正常运行,并且能够正确地创建对象并初始化,实现了题目要求。
阅读全文