How to initialize private static members in C++?

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

    I don't have enough rep here to add this as a comment, but IMO it's good style to write your headers with #include guards anyway, which as noted by Paranaix a few hours ago would prevent a multiple-definition error. Unless you're already using a separate CPP file, it's not necessary to use one just to initialize static non-integral members.

    #ifndef FOO_H
    #define FOO_H
    #include "bar.h"
    
    class foo
    {
    private:
        static bar i;
    };
    
    bar foo::i = VALUE;
    #endif
    

    I see no need to use a separate CPP file for this. Sure, you can, but there's no technical reason why you should have to.

提交回复
热议问题