We declare a variable staticin the class and initialize the variable outside the class, but we use the variable inside the function.
static
Anyone tell me the reason? Thanks at Advance
I am not sure, but I suppose, because only variables are declared inside the class member variables. They are initialized through the constructor or other member functions.
This happens when an object is created. However, objects must not be created for static members. Therefore, they must be initialized outside the class.
EDIT:, . , .
- -.
, :
struct Example { static int counter; Example() { counter++; } };
Example, , Example::counter. . ? ++, Stroustrup , (.. .cpp) , , "" . -
Example
Example::counter
.cpp
// Only in one .cpp file int Example::counter = 0;
(, , , , ).
.
, .
, . , .
, , , , .
, , , , cfront; , "static_members_of_everything.cpp" . , , .
A declaration within a class only declares a variable in this area. The definition actually allocates memory.
You use it inside class functions because it is defined in this area. Initialization of static variables does not occur during object creation, but rather at application startup.