2)定义学生类Student,包含学号、姓名、年龄和n门课的成绩(n由用户输入),要求: 键盘输入信息对一个学生对象初始化: 求学生的平均成绩。 输出所有信息。c++
时间: 2024-02-25 15:55:32 浏览: 38
下面是实现学生类的 C++ 代码:
```c++
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
string id; // 学号
string name; // 姓名
int age; // 年龄
int num; // 课程数
float* scores; // 成绩数组
public:
Student() {
cout << "请输入学生的学号:" << endl;
cin >> id;
cout << "请输入学生的姓名:" << endl;
cin >> name;
cout << "请输入学生的年龄:" << endl;
cin >> age;
cout << "请输入学生的课程数:" << endl;
cin >> num;
scores = new float[num]; // 动态分配成绩数组的内存
cout << "请输入学生的所有成绩(用空格分隔):" << endl;
for (int i = 0; i < num; i++) {
cin >> scores[i];
}
}
~Student() {
delete[] scores; // 释放成绩数组的内存
}
float getAverageScore() {
float sum = 0.0;
for (int i = 0; i < num; i++) {
sum += scores[i];
}
return sum / num;
}
void printInfo() {
cout << "学号:" << id << endl;
cout << "姓名:" << name << endl;
cout << "年龄:" << age << endl;
cout << "课程数:" << num << endl;
cout << "平均成绩:" << getAverageScore() << endl;
cout << "所有成绩:";
for (int i = 0; i < num; i++) {
cout << scores[i] << " ";
}
cout << endl;
}
};
int main() {
Student stu;
stu.printInfo();
return 0;
}
```
该程序可以根据用户输入的信息创建一个学生对象,并且可以计算该学生的平均成绩,最后输出该学生的所有信息。注意,为了避免内存泄漏,需要在类的析构函数中释放成绩数组的内存。