How to initialize private static members in C++?

What is the best way to initialize a private, static data member in C++? I tried this in my header file, but it gives me weird linker errors:

class foo
{
    private:
        static int i;
};

int foo::i = 0;

I'm guessing this is because I can't initialize a private member from outside the class. So what's the best way to do this?


The class declaration should be in the header file (Or in the source file if not shared).
File: foo.h

class foo
{
    private:
        static int i;
};

But the initialization should be in source file.
File: foo.cpp

int foo::i = 0;

If the initialization is in the header file then each file that includes the header file will have a definition of the static member. Thus during the link phase you will get linker errors as the code to initialize the variable will be defined in multiple source files.

Note: Matt Curtis: points out that C++ allows the simplification of the above if the static member variable is of const int type (eg int , bool , char ). You can then declare and initialize the member variable directly inside the class declaration in the header file:

class foo
{
    private:
        static int const i = 42;
};

For a variable :

foo.h:

class foo
{
private:
    static int i;
};

foo.cpp:

int foo::i = 0;

This is because there can only be one instance of foo::i in your program. It's sort of the equivalent of extern int i in a header file and int i in a source file.

For a constant you can put the value straight in the class declaration:

class foo
{
private:
    static int i;
    const static int a = 42;
};

For future viewers of this question, I want to point out that you should avoid what monkey0506 is suggesting.

Header files are for declarations.

Header files get compiled once for every .cpp file that directly or indirectly #includes them, and code outside of any function is run at program initialization, before main() .

By putting: foo::i = VALUE; into the header, foo:i will be assigned the value VALUE (whatever that is) for every .cpp file, and these assignments will happen in an indeterminate order (determined by the linker) before main() is run.

What if we #define VALUE to be a different number in one of our .cpp files? It will compile fine and we will have no way of knowing which one wins until we run the program.

Never put executed code into a header for the same reason that you never #include a .cpp file.

include guards (which I agree you should always use) protect you from something different: the same header being indirectly #include d multiple times while compiling a single .cpp file

链接地址: http://www.djcxy.com/p/17290.html

上一篇: 什么是C ++函数中静态变量的生命周期?

下一篇: 如何初始化C ++中的私有静态成员?