Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2508580
  • 博文数量: 308
  • 博客积分: 5547
  • 博客等级: 大校
  • 技术积分: 3782
  • 用 户 组: 普通用户
  • 注册时间: 2009-11-24 09:47
个人简介

hello world.

文章分类

全部博文(308)

分类: C/C++

2010-11-18 11:26:18

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

#include <iostream>
using namespace std;

class Student
{
    public:
    Student(int = 0,int = 0);
    void display();
    void max(Student * ,int); //定义找出最大成绩元素的函数

    
    private:
    int no;
    int score;
};

Student::Student(int no,int score):no(no),score(score){}
void Student::display()
{
    cout <<"no:" << no << " score:" << score << endl;
}

void Student::max(Student * stu,int n)
{
     Student *max_stu = stu; //设计第一个元素为最大元素

     
     for (int i = 0; i < n; i++)
     {
         if ((*stu).score > (*max_stu).score)
         {
             max_stu = stu;
         }
         stu++;
     }
     
     (*max_stu).display(); //输出最大元素的信息

}
 

int main()
{
    //定义对象数组

    Student stu[5] =
    {
        Student(1,100),
        Student(2,200),
        Student(3,300),
        Student(4,400),
        Student(5,500)
    };
    
    Student *p;//指定对象指针

    p = stu; //将对象数组的首地址赋值给指针对象

    (*p).max(p,5); //调用max函数,找出成绩最高者,并输出学生的成绩。

    system("pause");
    return 0;
}


阅读(2944) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~