2017-08-10 216 views
-4

我到处看到静态成员函数不能是const。在下面的代码中,当我尝试使用静态成员函数为const的代码块执行此操作时,我确实得到了输出。那么,这可能吗?还是仅支持更新版本的C++?Const静态成员函数

#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 
+4

该函数不是恒定的。它返回的int是。 –

+0

我已经指定了静态函数const –

+0

如果你想要一个方法是const,那么'const'就会结束。如果你把它放在开始处,它的返回值是'const' – litelite

回答

1

const预选赛成员函数必须在函数的参数列表中写到,它是不允许的静态成员函数中:

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

你声明的函数返回const int相反,虽然它并没有太大的也可以。