How to initialize private static members in C++?

后端 未结 17 2308
忘掉有多难
忘掉有多难 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:18

    With a Microsoft compiler[1], static variables that are not int-like can also be defined in a header file, but outside of the class declaration, using the Microsoft specific __declspec(selectany).

    class A
    {
        static B b;
    }
    
    __declspec(selectany) A::b;
    

    Note that I'm not saying this is good, I just say it can be done.

    [1] These days, more compilers than MSC support __declspec(selectany) - at least gcc and clang. Maybe even more.

提交回复
热议问题