2017-08-10 134 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相反,雖然它並沒有太大的也可以。