友元函数求全班同学平均绩点
时间: 2024-06-15 19:07:25 浏览: 16
友元函数是在C++中用来访问类的私有成员的一种特殊函数。它可以在类的外部定义,但是可以访问类的私有成员变量和成员函数。友元函数可以用来实现一些特殊的操作,比如求全班同学的平均绩点。
下面是一个示例代码,演示了如何使用友元函数来求全班同学的平均绩点:
```cpp
#include <iostream>
using namespace std;
class Student {
private:
string name;
float gpa;
public:
Student(string n, float g) {
name = n;
gpa = g;
}
friend float calculateAverageGPA(Student* students, int numStudents);
};
float calculateAverageGPA(Student* students, int numStudents) {
float totalGPA = 0;
for (int i = 0; i < numStudents; i++) {
totalGPA += students[i].gpa;
}
return totalGPA / numStudents;
}
int main() {
const int numStudents = 5;
Student students[numStudents] = {
Student("Alice", 3.5),
Student("Bob", 3.2),
Student("Charlie", 3.8),
Student("David", 3.6),
Student("Eve", 3.9)
};
float averageGPA = calculateAverageGPA(students, numStudents);
cout << "全班同学的平均绩点为:" << averageGPA << endl;
return 0;
}
```
在上面的代码中,我们定义了一个名为`Student`的类,其中包含了学生的姓名和绩点。然后,我们在类的内部声明了一个友元函数`calculateAverageGPA`,用来计算全班同学的平均绩点。在`calculateAverageGPA`函数中,我们可以直接访问`Student`类的私有成员变量`gpa`,并计算出总绩点。最后,我们在`main`函数中创建了一个包含5个学生对象的数组,并调用`calculateAverageGPA`函数来求全班同学的平均绩点。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)