我在程序错误计数的对象的总数量与静态变量

问题描述:

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。 –

在一个类的成员函数声明删除静态关键字

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

static关键字具有一个函数定义不同的含义,以static关键字。前者表示该函数不需要该类的实例(没有获取指针),后者定义了静态链接:对文件是本地的,该功能仅在该特定文件中可访问。

您还缺少count的定义。你需要一个地方行前main

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

我更新了我的答案 – dmitri

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

在C++中声明静态成员函数时,只能在类定义中声明它为static。如果您在类定义之外实现该功能(如您所用),请不要在此处使用static关键字。

在类定义之外,函数或变量的关键字static意味着该符号应该具有“静态链接”。这意味着它只能在它所在的源文件(翻译单元)内进行访问。当您将所有编译的源文件与链接的连接在一起时,static符号不会共享。如果您不熟悉术语“翻译单元”,请参阅this SO question

您还有一个问题,Saurav Sahu提到:您声明了静态变量static int count;,但从未定义它。添加类定义的这个之外:

int Sample::count = 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; 
}