设计一个学生类(Student),包含一个根据实际学生人数计算平均分的成员函数。 建立一个对象数组,存放3个学生的数据(学号、成绩),调用该成员函数求这3个学生的平均成绩。
时间: 2024-02-21 08:57:22 浏览: 21
好的,这是一个简单的学生类的实现:
```cpp
#include <iostream>
using namespace std;
class Student {
public:
int id;
int grade;
static int count; // 静态成员变量,记录学生人数
Student(int id, int grade) {
this->id = id;
this->grade = grade;
count++; // 每创建一个学生对象,人数加1
}
static double average(Student students[], int n) {
double sum = 0;
for (int i = 0; i < n; i++) {
sum += students[i].grade;
}
return sum / n;
}
};
int Student::count = 0;
int main() {
Student students[] = {
Student(1, 90),
Student(2, 80),
Student(3, 70)
};
double avg = Student::average(students, Student::count);
cout << "平均成绩为:" << avg << endl;
return 0;
}
```
这里定义了一个 `Student` 类,包含学号和成绩两个成员变量,以及一个静态成员变量 `count`,用于记录学生人数。同时,还定义了一个静态成员函数 `average`,用于计算给定学生数组的平均成绩。
在 `main` 函数中,创建了一个包含 3 个学生对象的数组 `students`,并调用 `average` 函数计算平均成绩。最后输出平均成绩即可。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)