求学生平均成绩代码分享
#include
#include
using namespace std;
class Student
{
private:
string name; // 姓名(私有)
double score; // 成绩(私有)
static int stuNum; // 静态:学生总数
static double sumScore; // 静态:总成绩
public:
// 构造函数:初始化成员 + 静态数据累加
Student(string n, double s) : name(n), score(s)
{
stuNum++;
sumScore += s;
}
// 静态函数:获取总人数 static int getStuNum() { return stuNum; } // 静态函数:计算平均分 static double getAvg() { if (stuNum == 0) return 0; return sumScore / stuNum; }};
// 静态成员,类外初始化
int Student::stuNum = 0;
double Student::sumScore = 0;
int main()
{
// 创建3个学生对象
Student s1(“张三”, 85);
Student s2(“李四”, 92);
Student s3(“王五”, 78);
cout << "学生总人数:" << Student::getStuNum() << endl; cout << "平均分:" << Student::getAvg() << endl; return 0;}
