cpp-静态成员和函数

cpp- static member and function

本文关键字:函数 静态成员 cpp-      更新时间:2023-10-16

我有下面的学生类,它有两个类似的函数-一个是静态的,一个不是。

class Student
{
    public:
        Student(std::string name_ , int const id_);
        virtual ~Student();
        void addGrade(int const grade2add);//grade above 100
        void removeGrade (int const grade2remove);  //update maxGrade
        void print(); //id, name, grades
        int getStudentMaxGrade();
        static int getMaxGrade();
    private:
        std::string name;  //max 20 chars
        int const id; //5 digits, only digits
        std::vector<int> grades;
        float avg;
        static int  maxGrade;
};

static int maxGrade使用0进行初始化。

我实现的功能:

int Student::maxGrade = 0;
int Student::getStudentMaxGrade()
{
    return *max_element(grades.begin(), grades.end());
}

我不知道如何实现静态函数。我试过了:

int Student::getMaxGrade()
{
     maxGrade= *max_element(grades.begin(), grades.end());
    return maxGrade;
}

但它不起作用(不能编译)

按照你的数据布局方式,每个学生对其他学生的成绩一无所知,而这个班对任何特定学生的成绩也一无所知。这是一个很好的封装,但为了检索所有学生的最高成绩,您必须包含一些逻辑来跟踪输入的最高成绩。类似这样的东西:

void Student::addGrade (int const grade) {
    // do the stuff, add the grade
    if (grade > maxGrade)  // Check if the grade is higher than the previous
        maxGrade = grade;  // highest recorded grade and, if so, overwrite it.
}

这样,每输入一个更高的分数,它就成为新的最高分数,这样,班级就永远知道最高分数,而不必跟踪每个学生的分数。