引自免费微信小程序:皆我百晓生
为了满足你的需求,下面是一个完整的C++代码示例,它实现了CStudent类的定义,包括构造函数、成员函数ShowData()和setData(),以及如何使用这些功能来处理学生数据并输出结果。
#include <iostream>
#include <string>
using namespace std;
class CStudent {
private:
string name;
string studentID;
string major;
int grade;
float score1, score2, score3;
float averageScore;
public:
// Constructor that initializes the attributes and calculates the average score
CStudent(string na, string id, string maj, float s1, float s2, float s3) {
name = na;
studentID = id;
major = maj;
grade = 0; // Assuming grade is not provided and set to a default value
score1 = s1;
score2 = s2;
score3 = s3;
calculateAverage();
}
// Function to calculate the average score
void calculateAverage() {
averageScore = (score1 + score2 + score3) / 3;
}
// Function to display student data
void ShowData() {
cout << "Name: " << name << ", ID: " << studentID << ", Major: " << major
<< ", Scores: " << score1 << " " << score2 << " " << score3
<< ", Average Score: " << averageScore << endl;
}
// Function to set student data
void setData(string na, string id, string maj, float s1, float s2, float s3) {
name = na;
studentID = id;
major = maj;
score1 = s1;
score2 = s2;
score3 = s3;
calculateAverage();
}
};
int main() {
int n;
cin >> n;
CStudent students[n];
for (int i = 0; i < n; i++) {
string na, id, maj;
float s1, s2, s3;
cin >> na >> id >> maj >> s1 >> s2 >> s3;
students[i] = CStudent(na, id, maj, s1, s2, s3);
}
for (int i = 0; i < n; i++) {
cout << i+1 << ",";
students[i].ShowData();
}
return 0;
}
这段代码首先包含了必要的头文件,并定义了CStudent类。类中包含私有成员变量用于存储学生的信息,以及公有成员函数用于初始化、显示和设置学生数据。main()函数读取学生数量和每个学生的信息,创建CStudent对象数组,并调用ShowData()函数来显示每个学生的信息和平均分数。
请注意,上述代码中的grade属性在构造函数中被设为了默认值0,因为题目中并未提及年级的具体赋值方式。如果你有特定的需求或数据输入方式,请调整这部分代码以适应实际场景。