定义一个student类,在该类定义中包括:一个数据成员(分数score)及两个静态数据成员(总分total和学生人数count);成员函数scoretotalcount(double s) 用于设置分数、求总分和累计学生人数;静态成员函数sum()用于返回总分;静态成员函数average()用于求平均值。
在main函数中,输入某班同学的成绩,并调用上述函数求全班学生的总分和平均分。
#include<iostream>
using namespace std;
class Student
{
public:
Student(string);
static float total;
static int count;//定义静态数据成员
void scoretotalcount(float s);
static float sum();
static float average();//定义静态成员函数
private:
string name;
float score;
};
int Student::count = 0;
float Student::total = 0;
Student::Student(string name)
{
this->name = name;
count++;
}//录入学生姓名
void Student::scoretotalcount(float s)
{
score = s;
total += s;
}//录入学生成绩并随录入计算总分
float Student::sum()
{
return total;
}//返回全班总分
float Student::average()
{
return total / count;
}//返回全班平均分
int main()
{
Student student1("xiaowang");
student1.scoretotalcount(90.5);
Student student2("xiaoming");
student2.scoretotalcount(93.5);
cout << "全班总分为:" << Student::sum() << endl;
cout << "全班平均分为:" << Student::average() << endl;
return 0;
}
#include <iostream>
#include <vector>
using namespace std;
class Student
{
public:
Student() { ++m_count; }
~Student() {}
void setScore(double s) { m_score = s; m_total += s; }
// double score(void) { return m_score; }
// int count(void) { return m_count; }
static double sum(void) { return m_total; }
static double average(void) { return m_count == 0 ? 0.0f : m_total / m_count; }
public:
static double m_total;
static int m_count;
private:
double m_score = 0;
};
double Student::m_total = 0.0f;
int Student::m_count = 0;
int main()
{
std::vector<Student*> students;
while (true)
{
cout << "输入大于等于0的数为学生分数;\n输入小于0的数结束输入并统计\n";
cout << "请输入学生分数:";
double score = 0.0f;
cin >> score;
if (score < 0)
{
break;
}
else
{
auto stu = new Student;
stu->setScore(score);
students.push_back(stu);
}
}
cout << "总分:" << Student::sum() << endl;
cout << "平均分:" << Student::average() << endl;
system("pause");
}