static member variable when declared private

丶灬走出姿态 提交于 2019-11-30 02:01:48
Alok Save

When a static member variable is declared private in a class, how can it be defined?

In the very same way as you define a public static variable in your source(cpp) file.

int static_demo::a = 1;

Access specifiers will not give you error while defining the member. Access specifiers control the access of the member variables, defining a static variable is an excpetion which is allowed.

Compiles cleanly on Ideone here.

EDIT: To answer your Q after you posted code.
Your problem is not the definition of the static member. The error is because you are trying to access the private static member inside main. You cannot do that.

Private members of a class can only be accessed inside the class member functions, the same rule applies even to static members. To be able to modify/access your static members you will have to add a member function to your class and then modify/access the static member inside it.

in your .cpp:

int static_demo::a(0);

when this causes an error, it is most common that you either encountered a linker error for a multiply defined symbol (e.g. the definition was in the header), or that you may have tried to define it in the wrong scope. that is, if static_demo is in the namespace MON, it would be defined in the .cpp:

#include "static_demo.hpp"
int MON::static_demo::a(0);

for other types, it may simply have been an incorrect constructor.

The problem is not the definition, but the fact that in main() (that's not in the name scope of static_demo, and cannot see a being private), you do an assignment.

The definition of a is what you did at global scope, with int static_demo::a;. You simply need an initializer, if you want a not to start with an undefined value.

int static_demo::a = 1;

will solve the problem.

From than on, a can be manipulated only by functions in static_demo (of friend of it).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!