错误代码
#include <iostream>
#include <string>
using namespace std;
class Lion
{
public:
void setAge(int age)
{
this->age = age;
}
int getAge() const
{
return this->age;
}
static int getTotalCount() const//error
{
return totalLionsCount;
}
private:
int age = 0;
static int totalLionsCount;
};
Compile error:
error C2272: 'getTotalCount': modifiers not allowed on static member functions
原因:
int getAge() const
等价与:
int getAge(const Lion* const this)
const类型的成员函数相当于传入了一个隐藏的const类型的this指针, 该指针指向Lion class 的一个实例,并且这个实例是const类型, 该this指针只能读取数,不能修改成员变量
但是static是属于class的,无法获取object的this指针, 综上,所以无法声明为const类型。
Reference:
C++: Why static member functions of a class can’t be const?
标签:const,int,age,static,类型,class,指针 From: https://blog.csdn.net/lianyunwangqian/article/details/142816997