C++ 对象数组和对象指针 实验

建立一个对象数组,要存放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;
	
}

运行截图如下:


代码仅供参考

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值