建立一个对象数组,要存放5个学生的数据(学号\成绩),用指针指向数组首元素,输出第1,3,5个学生的信息。再设立一个成员函数max,用指向对象的指针作为函数参数,在max函数中找出5个学生成绩最高者,并输出其学号。
代码\运行结果如下:
头文件代码如下:
#pragma once
class stu {
private:
int num; //学号
float score; //成绩
public:
stu(); //构造函数
void Student(int n, float s); //输入学号,成绩
void display();//输出学生信息
int getnum();//得到学号
float getscore();//得到成绩
stu max(stu s1, stu s2); //比较两个学生之前的成绩高低
};
main文件如下:
#pragma once
#include<iostream>
using namespace std;
class stu {
private:
int num;
float score;
public:
stu();
void Student(int n, float s);
void display();
int getnum();
float getscore();
stu max(stu s1, stu s2);
};
stu::stu() {
num = 0;
score = 0;
}
void stu::Student(int n, float s) {
num = n;
score = s;
}
void stu::display() {
cout << "num=" << num << " " << "score" << score << endl;
};
int stu::getnum() {
return num;
};
float stu::getscore() {
return score;
}
stu stu::max(stu s1, stu s2) {
stu m=s1;
if (m.getscore()<=s2.getscore())
{
m = s2;
}
return m;
};
void main()
{
stu st[5];
int n, s;
cout << "请输入五位同学的学号 成绩(空格隔开):" << endl;
for (int i = 0; i < 5; i++)
{
cin >> n >> s;
st[i].Student(n,s);
}
cout << "第1,3,5个学生的信息:" << endl;
for (int i = 0; i < 5; i=i+2)
{
st[i].display();
}
stu ma=st[0];
for (int i = 1; i < 5; i++)
{
ma=st[1].max(ma, st[i]);
}
cout << "五个学生中最高分的学生的学号是" << ma.getnum()<<"分数是:"<<ma.getscore()<< endl;
}
运行截图如下:
代码仅供参考