建立一个对象数组,内放5个学生的数据(学号,成绩),用指向对象的指针做函数参数,在max函数中找出5个学生中成绩最高者,并输出其学号。

来源:互联网 发布:.域名的续费是怎么回事 编辑:程序博客网 时间:2024/05/17 08:01

源代码如下:主要注意友元函数的声明

#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;
}



0 1
原创粉丝点击