Why can't I initialize a static field in C ++

Possible duplicate:
Defining static members in C ++

I work a bit in C ++ and I don’t understand how to use static fields in C ++, they seem to be useless. Please correct me.

I can not do it:

class AClass{
    public:
        static int static_field = 0;
};

And WHAT doesn't work.

class AClass{
    public:
        static int static_field;
};

int main(){
    int AClass::static_field = 0;
    return 0;
}
+5
source share
4 answers

You must initialize static_field outside the scope of the main function.

int AClass::static_field = 0;
int main(){
}
+9
source

Actually, you were close.

You must move: int AClass::static_field = 0;outside main()so that it is global in the CPP file, preferablyAClass.cpp.

, . main() , AClass::static_field , /.

PS: .

... , , . , . /, . , , , , .

+14

:

class AClass{
    public:
        static int static_field;
};

int AClass::static_field = 0;

int main(){
    return 0;
}
+4

When you declare a static variable here, you declare that there will be one instance of this variable, common to all instances of the class.

Moving an ad outside the core function, like some of the other answers provided, is the right decision.

Here are some docs from msdn for the static keyword:

http://msdn.microsoft.com/en-us/library/s1sb61xd.aspx

hope this helps

+4
source

All Articles