How to initialize private static members in C++?

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

    One "old-school" way to define constants is to replace them by a enum:

    class foo
    {
        private:
            enum {i = 0}; // default type = int
            enum: int64_t {HUGE = 1000000000000}; // may specify another type
    };
    

    This way doesn't require providing a definition, and avoids making the constant lvalue, which can save you some headaches, e.g. when you accidentally ODR-use it.

提交回复
热议问题