使用友元函数,Student类包含私有数据成员学生姓名、成绩。全局函数sum()计算总人数、总成绩;全局函数aver()计算n个学生的平均成绩(函数参数自己设定)。补充完成下列程序。 #include using namespace std; static int sum_score=0, count=0; //补充代码 int main() { Student stu[5] ={Student("Ma",89),Student("Hu",90),Student("LU",95), Student("Li",88),Student("Gao",75)}; for(int i=0;i<5;i++) sum(stu[i]); cout<<sum_score<<"," <<count<<endl; cout<<"Average="<<aver()<<endl; }
时间: 2023-06-08 14:04:24 浏览: 83
C++之友元:友元函数和友元类详解
5星 · 资源好评率100%
下面是使用友元函数的Student类程序,并且实现了全局函数sum()和aver():
#include<iostream>
#include<string>
using namespace std;
class Student{
private:
string name; //学生姓名
int grade; //成绩
public:
Student(string name, int grade) {
this->name = name;
this->grade = grade;
}
friend void sum(Student* students, int n); //声明sum()为友元函数
friend float aver(Student* students, int n); //声明aver()为友元函数
};
void sum(Student* students, int n) {
int totalScore = 0;
for (int i = 0; i < n; i++) {
totalScore += students[i].grade;
}
cout << "总人数:" << n << endl;
cout << "总成绩:" << totalScore << endl;
}
float aver(Student* students, int n) {
int totalScore = 0;
for (int i = 0; i < n; i++) {
totalScore += students[i].grade;
}
return (float)totalScore / n;
}
int main() {
Student students[] = {
{"小明", 80},
{"小红", 90},
{"小华", 95},
{"小李", 85},
{"小张", 92}
};
int n = sizeof(students) / sizeof(Student);
sum(students, n); //调用sum()计算总人数和总成绩
cout << "平均成绩:" << aver(students, n) << endl; //调用aver()计算平均成绩
return 0;
}
阅读全文