xx2003xxx 2022-10-09 16:54 采纳率: 50%
浏览 46
已结题

关于#C++#类的问题,如何解决?急

C++问题
设计并定义学生类,结合实际合理设置类的常成员、静态成员、友元函数等。编写nain()函数计算一个班10个学生某门课的平均成绩。
设计思路:
描述学生属性的基本数据有学号、姓名、成绩、总人数等,其中学号一旦给定就不允许修改,总人数为所有学生共享;基本操作有对象成员初始化、通过输入的方式设置学生信息、输出学生信息、获取学生成绩、获取学生总人数等。
一个班10个学生,定义学生类的对象数组存放。类外设置一个普通函数求10个学生成绩的平均分。

  • 写回答

1条回答 默认 最新

  • qfl_sdu 2022-10-09 16:58
    关注

    网上能都到类似的例子,代码如下:

    
    #include <iostream>
    #include <string>
    using namespace std;
    
    class Student
    {
    private:
        int mId;  //学号
        string mName;
        string mSex;
        int mScore;
        static int count; //总学生人数
    public:
        Student() {}
        Student(int id,string name, string sex, int score)
        {
            mId = id;
            mName = name;
            mSex = sex;
            mScore = score;
            count++;
        }
        ~Student()
        {
            count--;
        }
    
        //友元函数
        friend ostream& operator <<(ostream& out, Student&);
        friend istream& operator >>(istream& in, Student&);
    
        //获取学生人数
        static int GetStudentCount() { return count; }
    
        //获取学生分数
        int GetScore() { return mScore; }
    
    
    };
    
    int Student::count = 0;
    
    ostream& operator <<(ostream& out, Student& stu)
    {
        out << "学号:" << stu.mId << ",姓名:" << stu.mName << ",性别:" << stu.mSex << ",成绩:" << stu.mScore;
        return out;
    }
    istream& operator >>(istream& in, Student& stu)
    {
        in >> stu.mId >> stu.mName >> stu.mSex >> stu.mScore;
        return in;
    }
    
    //计算学生平均成绩
    void Average(Student stu[])
    {
        int nmb = Student::GetStudentCount();
        float sum = 0;
        for (int i = 0; i < nmb; i++)
        {
            sum += stu[i].GetScore();
        }
        cout << nmb << "个学生的平均成绩为:" << sum / nmb << endl;
    }
    
    int main()
    {
        Student stu[10];
        for (int i = 0; i < 10; i++)
        {
            cout << "请输入第" << i + 1 << "个学生的学号 姓名 性别 成绩:";
            cin >> stu[i];
            //cout << stu[i];
        }
        Average(stu);
        return 0;
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 10月17日
  • 已采纳回答 10月9日
  • 创建了问题 10月9日

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。