cpp-静态成员和函数
cpp- static member and function
我有下面的学生类,它有两个类似的函数-一个是静态的,一个不是。
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.
}
这样,每输入一个更高的分数,它就成为新的最高分数,这样,班级就永远知道最高分数,而不必跟踪每个学生的分数。
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 如何在C++中使用非静态成员函数作为回调函数
- 在作为静态成员包含在另一个类中的类的构造函数中使用 cout
- 静态成员函数使用相同的名称时出现模板类型名称错误
- 在 nullptr 上调用无状态类的非静态成员函数是否合法?
- 如何在友元函数中使用静态成员而不添加前缀 [类名]::
- C++构造函数和静态成员
- 为什么传递非静态成员函数会导致编译错误?
- 非静态成员失败的线程调用函数
- 处理类内的回调时,必须调用对非静态成员函数的引用
- 非静态成员函数的 decltype 格式不正确吗?
- 为什么 std::sort 找不到合适的(静态成员)函数重载?
- std::异步与非静态成员函数
- C++无效使用非静态成员函数?
- 指向重载静态成员的函数指针 - 在unique_ptr中用作自定义删除器
- 未使用的C++未优化的静态成员函数/变量
- C++:如何返回指向非静态成员函数的指针?
- 有没有一种方法可以使全局函数/静态成员函数一次可呼出
- 函数静态成员变量
- 隐藏模板化的辅助函数——静态成员或未命名的命名空间