how to initialize a variable which is private static?
It has to be initialized from within the class (private), and being static it can either be accessed through a static method or a member method. In the latter case you must take care so that instances of the object do not try to initialize a previously initialized. It is a basic type, you can initialize where you define it. If the static field is const, it can also be initialized in the class definition.
X.h
class X
{
private:
static int x;
static int y;
static const int z = 30; /*for the const variable, when you declare, you should initialize*/
public:
static void initClass() { x = 10; }
};
X.cpp
int X::x;
int X::y = 20;//???
const int X::z;//???
Note only static const variable can be initialed in the class or struct
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment