第4周專案4-指向學生類的指標

不被看好的青春叫成長發表於2015-03-29
*  
 * Copyright (c) 2015, 煙臺大學計算機學院  
 * All rights reserved.  
 * 檔名稱:test.cpp  
 * 作    者:劉暢   
 * 完成日期:2015年 3 月 27 日  
 * 版 本 號:v1.0  
 * 
 * 問題描述: 設計一個學生類Student,資料成員包括學號(num)和成績(score),成員函式
             根據需要自行設計(建議配備需要的set、get函式,以及必要的輸入或輸出,
             給出的程式碼中也可以找到需要成員函式的線索)。在main函式中,要做到:
             建立一個物件陣列,通過初始化,設定5個學生的資料,要求:
             用指標指向陣列首元素,輸出第1、3、5個學生的資訊;
             設計一個函式int max(Student *arr);,用指向物件的指標作函式引數,在max函式中找出5個學生中成績最高者,並返回值其學號。
 * 輸入描述:NULL;
 * 程式輸出:按要求輸出。


 

 

程式碼如下:

#include <iostream>
using namespace std;
class Student
{
public:
    Student(int x,double y):num(x),score(y) {};
    void output();
    double set_score()
    {
        return score;
    }
    int get_num()
    {
        return num;
    }
private:
    int num;   //學號
    double score;   //成績
};

//max函式返回arr指向的物件陣列中的最高成績(max並不是成員函式,而是普通函式)
int max(Student *arr);
void Student::output()
{
    cout<<num<<" "<<score<<endl;
}

int main()
{
    Student stud[5]=
    {
        Student(101,78.5),Student(102,85.5),Student(103,100),
        Student(104,98.5),Student(105,95.5)
    };
    //輸出第1、3、5個學生的資訊(用迴圈語句)
    for (int i=0; i<5; i+=2)
    {
        cout<<"學生"<<i<<":";
        stud[i].output();
    }
    //輸出成績最高者的學號
    cout<<"5個學生中成績最高者的學號為: "<<max(stud);//呼叫函式顯示最高成績
    return 0;
}


//定義函式max,返回arr指向的物件陣列中的最高成績,返回值為最高成績者的學號
int max(Student *arr)
{
//求最高成績及對應同學的學號
    double maxs=arr[0].set_score();
    int k=0;
    for (int i=1; i<5; i++)
    {
        if (arr[i].set_score()>maxs)
        {
            maxs=arr[i].set_score();
            k=i;
            }
    }
    return arr[k].get_num();

//返回最高成績者的學號

}


執行結果:

相關文章