How to initialize private static members in C++?

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

    The linker problem you encountered is probably caused by:

    • Providing both class and static member definition in header file,
    • Including this header in two or more source files.

    This is a common problem for those who starts with C++. Static class member must be initialized in single translation unit i.e. in single source file.

    Unfortunately, the static class member must be initialized outside of the class body. This complicates writing header-only code, and, therefore, I am using quite different approach. You can provide your static object through static or non-static class function for example:

    class Foo
    {
        // int& getObjectInstance() const {
        static int& getObjectInstance() {
            static int object;
            return object;
        }
    
        void func() {
            int &object = getValueInstance();
            object += 5;
        }
    };
    

提交回复
热议问题