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