类c ++中的静态成员未定义引用

用户名

为什么这段代码给了我一个错误的错误,该错误未定义引用student :: count。我正在使用静态计数,并且我知道静态成员默认情况下为0,但不知道为什么给我一个错误。请给我解释一下。

#include <iostream>
using namespace std;

class Student{

static int count;
string name;


public:

    Student(){
        count++;
        cout<<"I am  student"<<count<<endl;

    }
    int getCount() const
    {

        return count;
    }

    void setCount(int x){
        count=x;

    }


};

int main(){

Student stud[20];


return 0;
}
大卫·施瓦兹(David Schwartz)

没有定义Student::count,违反了一个定义规则将定义放在一个翻译单位中,并且只有一个。

请注意,如果static int count; 只是定义,则几乎无法使用静态成员。每次包含头文件时,您都会得到一个定义,这使得几乎不可能遵守一个定义规则。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章