建立一個物件陣列,內放5個學生的資料(學號,成績),用指向物件的指標做函式引數,在max函式中找出5個學生中成績最高者,並輸出其學號。
原始碼如下:主要注意友元函式的宣告
#include <iostream>
#include <string>
using namespace std;
class Student
{
public:
Student(string n,float s):number(n),score(s){}
friend void max(Student *); //宣告友元函式
private:
string number; //將學號宣告為字串
float score;
};
void max(Student *p)
{
int i;
for(i=0;i<5;i++)
{
if(p->score<(p+i)->score)
{
p=(p+1); //將指向較大值的指標賦給指向較小值的指標
}
}
cout<<"最高成績為:"<<p->score<<endl;
cout<<"學生學號為:"<<p->number;
}
int main()
{
Student Stud[5]={
Student("201024131101",99),
Student("201024131102",92),
Student("201024131103",99.5),
Student("201024131104",95),
Student("201024131105",93)
}; //定義一個物件陣列陣列並初始化物件
Student *p=Stud; //定義一個指向物件的指標
max(p); //呼叫函式
return 0;
}