学习记录——C++

定义一个学生类Student,包括3个数据成员:学号id,姓名name,分数score;两个静态数据成员:总分total和学生人数count;带参数的构造函数用来初始化对象,成员函数ChangeScore用来修改分数,静态成员函数GetAverage用来打印计算得到的平均分

我的第一篇博客
C++学习记录

#include <iostream>
#include <string>
using namespace std;
class Student
{
	public:
		Student(int id,string name,double score):id(id),name(name),score(score)	    //带参数的构造函数初始化对象
		{
			count++;
    		total+=score;
		}
		void ChangeScore(double newScore)
		{
			total+=newScore-score;    //因为是静态,所以定义一个新变量newScore 
			score=newScore;
		}
		static double GetAverage()
		{
			return total/count;
		}
	private:
		int id;
		string name;
		double score;
		static double total;
		static int count;
};
double Student::total=0.0f;
int Student::count=0;	// 类外对静态数据成员进行定义声明
int main()
{
	Student s1(01,"Wang",78);
	Student s2(02,"Liu",85);
	Student s3(03,"Chen",90);
	cout<<"The average score is:"<<Student::GetAverage()<<endl;	
	s1.ChangeScore(82);
	s2.ChangeScore(85);
	s3.ChangeScore(76);
	cout<<"The new average score is:"<<Student::GetAverage()<<endl;
}

运行结果:在这里插入图片描述