简体   繁体   English

如何通过仅在cpp文件中初始化静态成员的情况

[英]how to initialize a static member in cpp file only situation via a

I have a class in a cpp file. 我在cpp文件中有一个类。 There is no header file in my case: 我没有头文件:

class MyClassATest
{
     static Logging &logger = Logging::getInstance();

     static void testMethodA()
     {
          logger.logDebug(....);

     }

};

I tried several different ways try to make the first statement works: 我尝试了几种不同的方法来使第一个语句起作用:

constexpr static Logging &logger = Logging::getInstance();
static Logging const &logger = Logging::getInstance();
constexpr static Logging const &logger = Logging::getInstance();

Is there a way to initialize that logger variable in my case? 在我的情况下,有没有办法初始化该记录器变量?

EDIT: 编辑:

Following are the results in different cases: 以下是不同情况下的结果:

error: field initializer is not constant
         constexpr const static Logging &logger = Logging::getInstance();

error: field initializer is not constant
         constexpr static const BMLogging &logger = BMLogging::getInstance();

error: field initializer is not constant
         constexpr static BMLogging const &logger = BMLogging::getInstance();

error: field initializer is not constant
         constexpr static BMLogging &logger = BMLogging::getInstance();

You can initialize it outside the class, like this: 您可以在类外部对其进行初始化,如下所示:

// This goes in your CPP file at any point after the class declaration
Logging& MyClassATest::logger(Logging::getInstance());

Alternatively, you could put initialization in a static member function: 或者,您可以将初始化放在静态成员函数中:

static Logging& logger() {
    // Make a function-static variable instead of a class-static one
    static Logging &loggerInstance(Logging::getInstance());
    return loggerInstance;
}

In class member initialization is applicable to integral types only. 在类中,成员初始化仅适用于整数类型。 So, you have to initialize it out of class. 因此,您必须在类外对其进行初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM