常量静态成员函数

Const Static member function

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

我到处都看到静态成员函数不能是常量。在下面的代码中,当我尝试使用静态成员函数为 const 的代码块执行它时,我实际上得到了输出。那么,这可能吗?还是仅受较新版本的C++支持?

#include<iostream>
using namespace std;

class s{
public:static const int x=2;
const static int fun(){
return x+1;
}
};

int main(){
s obj;
cout<<obj.x<<endl;
cout<<obj.fun()<<endl;
return 0;
}
output: 2
3

成员函数的const限定符必须在函数参数列表之后编写,静态成员函数不允许这样做:

static int fun() const // error const qualifier is not allowed on static member function
{

你声明了一个返回const int的函数,尽管它也没有多大意义。