C++面向对象编程题 第21题

21.试定义一个处理学生信息的类Student。该类包含学号、成绩和姓名等数据成员(学号不能相同)以及若干成员函数,另外定义一外全局函数 max(),返回 n 个学生成绩最高者。

具体要求如下:

  1. 私有数据成员
  • int num,score; num 存放学号, score 存放成绩
  • char name[9]; name 存放学生的姓名
  1. 公有成员函数
  • 构造函数;将学号、成绩设置为 0,姓名设置为空
  • int check_num(Student str[],int n); 检查学号是否已经在 str 中存在,返回 1,否则返回 0。
  • void Set(int id,char *na,int sc);为数据成员赋值。
  • int get_score();返回学生成绩。
  • void print();输出学生的学号、姓名和成绩。
  1. Student max(Student *,int n);全局函数,求得并返回 s 所指向的 n 个学生中成绩最高者。
  2. 在主函数中完成对该类的测试,主函数中定义一个长度为 3 的 Student 类的对象数组 s, 依次键入学号、成绩、姓名;注意,在输入每一个学生的信息后,要判断所输入的学号是否已存在,如果存在,则要求重新输入该学生的信息。最后调用全局函数 max(),得到成绩最高的学生信息并输出。
#include<iostream>
#include<cstring>
using namespace std;
class Student{
    int num,score;
    char name[9];
public:
    Student(){
        num=0;
        score=0;
        name[0]='\0';
    }
    int check_num(Student str[],int n){
        for(int i=0;i<n-1;i++){
            if(str[i].num==str[i+1].num)return 1;
        }
        return 0;
    }
    void set(int id,int sc,char *na){
        num=id;
        score=sc;
        strcpy(name,na);
    }
    int get_score(){
        return score;
    }
    void print(){
        cout<<"name:"<<name<<",num:"<<num<<",score:"<<score<<endl;
    }
};
Student max(Student *s,int n){
    int max=s[0].get_score();
    int index=0;
    for(int i=1;i<n;i++){
        if(s[i].get_score()>max){
            index=i;
            max=s[i].get_score();
        }
    }
    return s[index];
}
int main(){
    Student s[3];
    for(int i=0;i<3;i++){
        int id,sc;
        char na[9];
        cout<<"please input num socre name:";
        cin>>id>>sc>>na;
        s[i].set(id,sc,na);
        while(i!=0&&s[i].check_num(s,3)){
            cout<<"num repeat,please input num socre name again:";
            cin>>id>>sc>>na;
            s[i].set(id,sc,na);
        }
    }
    max(s,3).print();
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值