零度碳酸☆ 2022-01-06 16:41 采纳率: 40%
浏览 97
已结题

c++定义学生类,有私有成员

定义学生类,有私有成绩属性score, 有公有函数show用来输出成绩,添加-一个静态数据成员totalscore, 用来计算所有学生的总成绩,再添加-一个公有静态函数成员Alll用来显示totalscore的值,要求类中要有构造函数、拷贝构造函数,析构函数,在主函数中定义不少于三个对象进行测试。

  • 写回答

1条回答 默认 最新

  • 吉拉尔 2022-01-06 21:17
    关注
    #include <iostream>
    using namespace std;
    
    class Student
    {
    private:
        int score;
        static int totalscore;
    
    public:
        Student(int s) : score(s) { totalscore += s; }
        Student(const Student &s)
        {
            score = s.score;
            totalscore += score;
        }
        ~Student() { totalscore -= this->score; }
        void show() { cout << "score: " << score << endl; }
        static void ALL() { cout << "total score: " << totalscore << endl; }
    };
    
    int Student::totalscore = 0;
    
    int main()
    {
        Student s1(50);
        s1.show();
        Student::ALL();
        // score: 50
        // total score: 50
    
        Student s2(60);
        s2.show();
        Student::ALL();
        // score: 60
        // total score: 110
    
        {
            // 赋值构造测试
            Student s3(s1);
            s3.show();
            Student::ALL();
            // score: 50
            // total score: 160
        } // 析构s3;
        Student::ALL();
        // total score: 110
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 4月4日
  • 已采纳回答 3月27日
  • 创建了问题 1月6日