用c++语言实现使用动态内存分配创建封装的动态学生类Student的对象数组class,在主函数中计算所有学生每门课程的平均成绩并输出。学生类Student中包含当前学生对象的姓名、学号和三门课程的成绩。在主函数中要求用户输入学生人数num,并根据输入的学生人数num创建动态对象数组
时间: 2023-12-10 20:38:27 浏览: 26
以下是用C++语言实现使用动态内存分配创建封装的动态学生类Student的对象数组class,在主函数中计算所有学生每门课程的平均成绩并输出的示例代码:
```c++
#include <iostream>
#include <string>
using namespace std;
class Student {
public:
Student(string name, string id, double score1, double score2, double score3) {
this->name = name;
this->id = id;
this->score1 = score1;
this->score2 = score2;
this->score3 = score3;
}
double getAvgScore() {
return (score1 + score2 + score3) / 3;
}
private:
string name;
string id;
double score1;
double score2;
double score3;
};
int main() {
int num;
cout << "请输入学生人数:";
cin >> num;
Student *p = new Student[num];
for (int i = 0; i < num; i++) {
string name, id;
double score1, score2, score3;
cout << "请输入第" << i + 1 << "个学生的姓名、学号、三门课程的成绩:" << endl;
cin >> name >> id >> score1 >> score2 >> score3;
p[i] = Student(name, id, score1, score2, score3);
}
double avgScore1 = 0, avgScore2 = 0, avgScore3 = 0;
for (int i = 0; i < num; i++) {
avgScore1 += p[i].getAvgScore() / num;
avgScore2 += p[i].getAvgScore() / num;
avgScore3 += p[i].getAvgScore() / num;
}
cout << "所有学生每门课程的平均成绩为:" << endl;
cout << "课程1:" << avgScore1 << endl;
cout << "课程2:" << avgScore2 << endl;
cout << "课程3:" << avgScore3 << endl;
delete[] p;
return 0;
}
```
注意,上述代码中使用了动态内存分配来创建动态对象数组,即通过new操作符创建了一个长度为num的Student类型指针数组p,并在循环中通过调用Student类的构造函数为每个元素赋值。在计算每门课程的平均成绩时,我们使用了循环遍历Student对象数组p并调用每个对象的getAvgScore()函数来获取平均成绩,最后求出每门课程的平均数。最后,我们需要使用delete[]操作符释放动态对象数组p所占用的内存。