码迷,mamicode.com
首页 > 其他好文 > 详细

第八周项目(4)—指向学生类的指针

时间:2016-05-12 15:01:40      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:

/*
*copyright (c) 2016,烟台大学计算机学院
*All rights reserved.
*文件名称:hellow.cpp
*作者:田甜
*完成日期:2016年5月10日
*版本号:v1.0
*
*问题描述:设计一个学生类Student,数据成员包括学号(num)和成绩(score),成员函数根据需要自行设计(建议配备需要的set、get函数,以及必要的输入或输出,给出的代码中也可以找到需要成员函数的线索)。在main函数中,要做到:
建立一个对象数组,通过初始化,设置5个学生的数据,要求:
用指针指向数组首元素,输出第1、3、5个学生的信息;
设计一个函数int max(Student *arr);,用指向对象的指针作函数参数,在max函数中找出5个学生中成绩最高者,并返回值其学号。
*输入描述://///
*程序输出:学生信息
*/



#include <iostream>

using namespace std;
class Student
{
public:
    Student(int n,double s):num(n),score(s){}
    void display();
    int get_num()
    {
        return num;
    }
    double get_score()
    {
        return score;
    }
private:
    int num;
    double score;
};

void Student::display()
{
    cout<<num<<" "<<score<<endl;
}
int max(Student *arr);
int main()
{
   Student stu[5]={Student(101,78.5),Student(102,85.5),Student(103,100),
   Student(104,98.5),Student(105,95.5)};
   for(int i=0;i<5;i++)
   {
       cout<<"学生"<<i+1<<":";
       stu[i].display();
   }
   cout<<"5个学生中成绩最高者的学号为:"<<max(stu);
    return 0;
}

int max(Student *arr)
{
    int k;
    double max_score=arr[0].get_score();
    for(int i=0;i<5;i++)
        if(arr[i].get_score()>max_score)
          {
              max_score=arr[i].get_score();
              k=i;
          }
    return arr[k].get_num();
}

运行结果:

技术分享

心得体会:

使用私有类成员时需要调用公有类的函数,因此要注意在类中定义。

对象数组的用法比较常规,跟之前学习的数组一样使用。

第八周项目(4)—指向学生类的指针

标签:

原文地址:http://blog.csdn.net/sweetsweet1997/article/details/51367430

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!