【C++之对象数组和对象指针2】找到成绩最高的学生

简介: 【C++之对象数组和对象指针2】找到成绩最高的学生

题目要求


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


——谭浩强的《C++面向对象程序设计》第3章习题第5小题


程序


student.h


/*
*************************************************************************
@file:    student.h
@date:   2020.11.7
@author: Xiaoxiao
@blog:    https://blog.csdn.net/weixin_43470383/article/details/109541159
*************************************************************************
*/
#include <iostream>
using namespace std;
class Student // 声明类类型
{
private: // 声明私有部分
  int num;   // 学号
  int score;       // 成绩
public: // 声明公用部分
  Student(int n, int s) : num(n), score(s) {}; // 定义带参数的构造函数,并用参数的初始化表对数据成员初始化
  void max(Student *);                         // 找到成绩最高的学生,并输出其学号
};


student.cpp


/*
*************************************************************************
@file:    student.cpp
@date:   2020.11.7
@author: Xiaoxiao
@blog:    https://blog.csdn.net/weixin_43470383/article/details/109541159
*************************************************************************
*/
#include"student.h"
// 类外定义成员函数
void Student::max(Student *arr)   // 找到成绩最高的学生,并输出其学号
{
  int max_score = arr[0].score; // 记下最高成绩
  int max_num = 0;              // 记下成绩最高的学生的学号
  for (int i = 0; i < 5; i++)
  {
  if (arr[i].score > max_score)
  {
    max_score = arr[i].score;
    max_num = i;
  }
  }
  cout << "The number of student who get the highest score:"<< endl << arr[max_num].num << endl;
}


main.cpp


/*
*************************************************************************
@file:    main.cpp
@date:   2020.11.7
@author: Xiaoxiao
@blog:    https://blog.csdn.net/weixin_43470383/article/details/109541159
*************************************************************************
*/
#include "student.h"
int main()
{
  Student stu[5] = {
  Student(1, 96),
  Student(2, 97),
  Student(4, 99),
  Student(8, 100),
  Student(16, 98)
  }; // 定义对象数组
  Student *p;    // 定义p为指向Student类对象的指针变量
  p = stu;       // 将stu的起始地址赋给p
  // 或:Student *p = stu;
  stu[5].max(p); // 调用对象stu[5]的公有成员函数max
  system("pause");
  return 0;
}


运行结果



相关文章
|
6天前
|
C++
【C++】智能指针
【C++】智能指针
|
4天前
|
编译器 C++
virtual类的使用方法问题之在C++中获取对象的vptr(虚拟表指针)如何解决
virtual类的使用方法问题之在C++中获取对象的vptr(虚拟表指针)如何解决
|
3天前
|
算法 Java
双指针在数组遍历中的应用
文章深入探讨了双指针技术在数组遍历中的应用,通过实战例子详细解释了快慢指针和首尾指针的不同用法,并提供了解决LeetCode相关问题的Java代码实现。
|
4天前
|
安全 编译器 容器
C++STL容器和智能指针
C++STL容器和智能指针
|
4天前
|
安全 编译器 C语言
|
6天前
|
C++
C++通过文件指针获取文件大小
C++通过文件指针获取文件大小
10 0
|
6天前
|
编译器 C语言 C++
【C++关键字】指针空值nullptr(C++11)
【C++关键字】指针空值nullptr(C++11)
|
6天前
|
算法 C++ 容器
【C++算法】双指针
【C++算法】双指针
|
2月前
|
C语言
指针进阶(C语言终)
指针进阶(C语言终)
|
5天前
|
C语言
【C初阶——指针5】鹏哥C语言系列文章,基本语法知识全面讲解——指针(5)
【C初阶——指针5】鹏哥C语言系列文章,基本语法知识全面讲解——指针(5)

热门文章

最新文章