C++实验二数组、指针和字符串

建立一个名为CStudent的类,该类有以下几个属性:学号、姓名(使用字符指针)、成绩,并为上述属性定义相应的方法。
用C++ 面向对象的程序设计方法,找到并输出存放在CStudent类动态数组中学生成绩最高的学生信息(需考虑分数相同的情况,输出学号、姓名和成绩)。

#include<iostream>
using namespace std;
class CStudent {
private:
	long Num;
	char* Name;
	float Score;
public:
	CStudent();
	CStudent(long num, char* name, float score);
	CStudent(CStudent& s);
	void Set(long num, char* name, float score);
	long GetNum();
	char* GetName();
	float GetScore();
	void Show();
	friend void Max(CStudent* s, int size);
	~CStudent();
};
CStudent::CStudent() :Num(0), Name(NULL), Score(0) {
	cout << "Default Constructor called." << endl;
}
CStudent::CStudent(long num, char* name, float score) : Num(num), Name(name), Score(score) {
	cout << "Constructor called." << endl;
}
CStudent::CStudent(CStudent& s) {
	Num = s.Num;
	Name = s.Name;
	Score = s.Score;
}
void CStudent::Set(long num, char* name, float score) {
	Num = num;
	Name = name;
	Score = score;
}
long CStudent::GetNum() {
	return Num;
}
char* CStudent::GetName() {
	return Name;
}
float CStudent::GetScore() {
	return Score;
}
void CStudent::Show()
{
	cout << "学号:" << Num << endl;
	cout << "姓名:" << Name << endl;
	cout << "成绩:" << Score << endl;
}
void Max(CStudent* s, int size)
{
	float max = s->GetScore();
	int i;
	for (i = 1; i < size; i++)
	{
		if (max < (s + i)->GetScore())
		{
			max = (s + i)->GetScore();
		}
	}
	for (i = 0; i < size; i++)
	{
		if (max == (s + i)->GetScore())
		{
			(s + i)->Show();
			cout << endl;
		}
	}
}
CStudent::~CStudent() {
	cout << "Destructor called." << endl;
}
int main()
{
	int Size;
	cout << "Please enter the number of students:" << endl;
	cin >> Size;
	CStudent* s = new CStudent[Size];
	s[0] = CStudent(20200520, "Tom", 98);
	s[1] = CStudent(20200521, "Bob", 100);
	cout << "成绩最高的学生信息为:" << endl;
	Max(s, Size);
	cout << "Delete..." << endl;
	delete[] s;
	return 0;
}

可以通过改变Size的值,从而在主函数里面增加其他数量的学生信息。
我这样写,运行时只需要输入学生的个数,不用输入有关学生的信息,从而更方便测试程序。

猜你喜欢

转载自blog.csdn.net/qq_45876197/article/details/106499115