Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/39.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何在仅cpp文件的情况下通过_C++ - Fatal编程技术网

C++ 如何在仅cpp文件的情况下通过

C++ 如何在仅cpp文件的情况下通过,c++,C++,我在cpp文件中有一个类。我的案例中没有头文件: class MyClassATest { static Logging &logger = Logging::getInstance(); static void testMethodA() { logger.logDebug(....); } }; 我尝试了几种不同的方法,试图让第一种说法奏效: constexpr static Logging &logger

我在cpp文件中有一个类。我的案例中没有头文件:

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

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

     }

};
我尝试了几种不同的方法,试图让第一种说法奏效:

constexpr static Logging &logger = Logging::getInstance();
static Logging const &logger = Logging::getInstance();
constexpr static Logging const &logger = Logging::getInstance();
在我的例子中,有没有办法初始化这个记录器变量

编辑:

以下是不同情况下的结果:

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();

类内成员初始化仅适用于整型。因此,您必须在类外对其进行初始化。

您可以在类外对其进行初始化,如下所示:

// This goes in your CPP file at any point after the class declaration
Logging& MyClassATest::logger(Logging::getInstance());
或者,您可以将初始化放在静态成员函数中:

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

你的解决方案现在到底有什么不起作用?这并不完全准确。对于C++11,类内成员初始化适用于静态的非整数类型,因为它们是constexpr。此外,即使非静态成员不是常量表达式,也可以在类中初始化它们(请参见和)@AtlasC1你说得对,谢谢!顺便说一下,当你看到像这样愚蠢的错误时,请随意编辑或建议编辑:当我在我的答案上看到它们时,我会很快批准它们。非常感谢你!编译错误消失了,但我得到了链接错误:该行对“Logging::getInstance()”的未定义引用。我检查了结果,我看到libloggint.a在那里。@5YrsLaterDBA这很奇怪:链接错误通常表示库不在那里,或者标头与库不匹配。对于某些链接器,您提到库的顺序可能需要更改,但这是假设您正在构建库,而不是可执行文件,然后尝试链接它。@dasblinkenlight现在有两个模块:logging和common,它们有彼此的引用。如果我更改链接序列,我会得到不同的错误,告诉我一些日志中未定义的常用方法。之前的错误是某些日志记录方法找不到共同点。有什么想法吗?