Initializing a private static variable in a class

I have a class in the header file:

class Employee
    {
        //Private data members
    private:
        string firstName;
        string lastName;
        char gender;

        //number of employees
        const static int numEmployees = 0;

    public: 
    ....
    };

The dumb case in "GUIDELINE" from the instructor says that declaring numEmployees as a static integer value 0 in a private member of the class

The problem is that I can’t update the variable numEmployees, since it const, for example, when you declare the constructor publicly: .. you cannot increase numEmployees = numEmployees + 1.

If you do not declare numEmployeeshow const, just make a static int numEmployees;visual studio 2010, report an error, inform that only the class constwill be declared in the class.

Any idea how to declare numEmployees? Thank!

+3
source share
4 answers

numEmployees

Employee::numEmployees = 0

public

static int numEmployees;

private , .

+1

numEmployees , const. , , , :

int Employee::numEmployees = 0;

, numEmployees Employee, , .

gender , char.

+5

++ , .

// --- .h interface file
class MyClass
{
    public:
        static int my_static_variable;
    ...
};

// --- .cpp implementation file
#include "myclass.h"
int MyClass::my_static_variable = 0;

, , .

- , :

class MyClass
{
    public:
        // Note: returning a reference to int!
        static int& my_static_variable()
        {
            static int n = 0;
            return n;
        }
};

:

MyClass::my_static_variable() = 0;
MyClass::my_static_variable() ++;
MyClass::my_static_variable() *= 2;

"", , inline, , , , , .

+2

const. const?

, static - , . .

+1

All Articles