如何正确使用静态私有变量 [英] how to use static private variable correctly

查看:62
本文介绍了如何正确使用静态私有变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我有这个错误,如果有人可以帮忙的话会很好。



在我的班级文件中我已声明如下:



Hi I am having this error and would be nice if someone could help.

In my class header file I have declared following:

class CStudentClass
{
private:

    static int m_currentNumberOfStudents;





但是当我尝试在.cpp文件中使用上面的私有变量时,我收到一条错误消息:





However when I try to use the above private variable in .cpp file I get an error saying:

1>StudentClass.obj : error LNK2001: unresolved external symbol "private: static int CStudentClass::m_currentNumberOfStudents" (?m_currentNumberOfStudents@CStudentClass@@0HA)
1>c:\my documents\Projects\Student_Class\Debug\Student_Class.exe : fatal error LNK1120: 1 unresolved externals
1







我做错了什么?谢谢



我尝试在我的.cpp文件中引用这个变量,使用:m_currentNumberOfStudents和CStudentClass :: m_currentNumberOfStudents但两者似乎都失败了?




What am I doing wrong? thanks

I tried referring to this variable in my .cpp file both using: m_currentNumberOfStudents and CStudentClass::m_currentNumberOfStudents but both seem to fail??

推荐答案

必须在.cpp文件中定义静态成员,如下所示:

Static members have to be defined inside the .cpp file, something like this:
int CStudentClass::m_currentNumberOfStudents = 0;





(除了课堂内的声明之外。)



(This is in addition to the declaration inside the class.)


这篇关于如何正确使用静态私有变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆