本帖最后由 倒戈卸甲 于 2020-4-24 00:32 编辑 /*
类实现
*/class Student
{
public:
Student() {
}
Student(int id,int age) {
this->id = id;
this->age = age;
}
int getId() {
return id;
}
void setId(int id) {
this->id = id;
}
int getAge() {
return age;
}
void setAge(int age) {
this->age = age;
}
private:
int id;
int age;
};
void test1() {
Student *stu= NULL;
int num;
cout << "请输入要统计的学生数量:" << endl;
cin >> num;
stu=new Student[num];
for (int i = 0; i < num; i++)
{
int id, age;
cout << "请输入第" << i+1 << "个学生信息:" << endl;
cout << "学号:\t";
cin >> id;
cout << "年龄:\t";
cin >> age;
stu[i] = Student(id, age);
}
int max = 0;
for (int i =1 ; i <num ; i++)
{
if (stu[i].getId()> stu[max].getId())
{
max = i;
}
}
cout << "最大学号是:"<< stu[max].getId() <<",这个学生的年龄是:" << stu[max].getAge() << endl;
delete stu;
}
/*
结构体实现
*/
struct Stu
{
int id;
int age;
};
void test2() {
Stu* stu = NULL;
int num;
cout << "请输入要统计的学生数量:" << endl;
cin >> num;
stu = new Stu[num];
for (int i = 0; i < num; i++)
{
int id, age;
cout << "请输入第" << i + 1 << "个学生信息:" << endl;
cout << "学号:\t";
cin >> id;
cout << "年龄:\t";
cin >> age;
stu[i] = Stu{ id, age };
}
int max = 0;
for (int i = 1; i < num; i++)
{
if (stu[i].id > stu[max].id)
{
max = i;
}
}
cout << "最大学号是:" << stu[max].id << ",这个学生的年龄是:" << stu[max].age << endl;
delete stu;
}
在主函数中调用test1或者test2即可 |