2016-08-03 22 views
1
using namespace std; 
class Sample 
{ int x; 
    static int count; 
    public: 
    void get(); 
    static void showCount(); 
}; 
void Sample::get() 
{ 
    cin>>x; 
    ++count; 
} 
static void Sample::showCount(){  
    cout<<"Total No. of Objects :"<<count; 
} 
int main() 
{ Sample s1,s2; 
    s1.get(); 
    s2.get(); 
    Sample::showCount(); 
    return 0; 

} 

編譯錯誤:[錯誤]不能聲明成員函數「靜態無效樣品:: showCount()」爲有靜態鏈接[-fpermissive]我在程序錯誤計數的對象的總數量與靜態變量

+1

一件事在你的代碼缺少的是count'的'初始化。靜態成員變量(這裏是'count')必須在類中聲明,然後在其外部定義。 –

+0

編譯器定義的默認count = 0。 –

回答

2

在一個類的成員函數聲明刪除靜態關鍵字

void Sample::showCount(){  
    cout<<"Total No. of Objects :"<<count; 
} 

static關鍵字具有一個函數定義不同的含義,以static關鍵字。前者表示該函數不需要該類的實例(沒有獲取指針),後者定義了靜態鏈接:對文件是本地的,該功能僅在該特定文件中可訪問。

您還缺少count的定義。你需要一個地方行前main

int Sample::count = 0; 
... 
main() { 
... 
} 
+0

我更新了我的答案 – dmitri

0
class Sample 
{ ... 
    static void showCount(); 
}; 

static void Sample::showCount(){  
    cout<<"Total No. of Objects :"<<count; 
} 
// You can void instead of static, because you are not returning anything. 

這是不正確。你不需要第二個static

0

在C++中聲明靜態成員函數時,只能在類定義中聲明它爲static。如果您在類定義之外實現該功能(如您所用),請不要在此處使用static關鍵字。

在類定義之外,函數或變量的關鍵字static意味着該符號應該具有「靜態鏈接」。這意味着它只能在它所在的源文件(翻譯單元)內進行訪問。當您將所有編譯的源文件與鏈接的連接在一起時,static符號不會共享。如果您不熟悉術語「翻譯單元」,請參閱this SO question

您還有一個問題,Saurav Sahu提到:您聲明瞭靜態變量static int count;,但從未定義它。添加類定義的這個之外:

int Sample::count = 0; 
0
#include <iostream> 
using namespace std; 
class Sample 
{ 
    int x; 
public: 
    static int count; 
    void get(); 
    static void showCount(); 
}; 
int Sample::count = 0; 
void Sample::get() 
{ 
    cin >> x; 
    ++count; 
} 
void Sample::showCount(){ 
    cout << "Total No. of Objects :" << count; 
} 
int main() 
{ 
    Sample s1, s2; 
    s1.get(); 
    s2.get(); 
    Sample::showCount(); 
    return 0; 
}