How to initialize private static members in C++?

后端 未结 17 2311
忘掉有多难
忘掉有多难 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条回答
  •  猫巷女王i
    2020-11-21 07:11

    What about a set_default() method?

    class foo
    {
        public:
            static void set_default(int);
        private:
            static int i;
    };
    
    void foo::set_default(int x) {
        i = x;
    }
    

    We would only have to use the set_default(int x) method and our static variable would be initialized.

    This would not be in disagreement with the rest of the comments, actually it follows the same principle of initializing the variable in a global scope, but by using this method we make it explicit (and easy to see-understand) instead of having the definition of the variable hanging there.

提交回复
热议问题