How to initialize private static members in C++?

后端 未结 17 2675
忘掉有多难
忘掉有多难 2020-11-21 07:04

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
{
           


        
17条回答
  •  南旧
    南旧 (楼主)
    2020-11-21 07:29

    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;
    };
    

提交回复
热议问题