When to use a C ++ static variable

I am a little confused about using variables static/ global/ global static/ extern.

I would like the counter variable to increment whenever the class is instantiated.

I would really appreciate it if someone could post an explanation of the appropriate use for each.

+4
source share
1 answer

According to the concept of OO, you should NEVER use global static variables. Instead, you can define a static variable in your class for the number of instances of your class. Make it closed so that no one other than your constructor can increase the counter. Provide a public function to get the counter. See the example below:

yourclass.h:

class YourClass {
private:
    static int instanceCount_;
public:
    YourClass() {++YourClass::instanceCount_;}  // constructor
    ~YourClass() {--YourClass::instanceCount_;} // destructor
    static int instanceCount() {return instanceCount_;}
};

yourclass.cpp:

int YourClass::instanceCount_ = 0;

Regarding the concept of static / global / global static / external 1.static: 1a) global static: Static variable, as shown below:

static int numberOfPersons;

This variable can only be seen in the file (it will not have a collision of names with another name of the same variable in other files)

1a) class static: ( ) , ( Class:: Var) ( " ", ). . ( ).

1b) . ( , "Class::", .

, 1a. 1b. , , er, , . .

  1. - "", :

    int numberOfPersons;

"" , "extern". . , .

  1. extern: /, . . 3., , , extern, , , . extern int numberOfPersons;

    int addPersonCount() {    numberOfPersons ++; }

, .

+3

All Articles