如何在C ++中的构造函数中定义extern const

hei*_*zel 4 c++ constants

两个config.json文件包含我想存储为常量的值。我的计划是在相应类的构造函数中加载并解析json文件,并将值分配给常量。但是,在调试模式下,会出现错误“ ... LNK2019:无法解析的外部符号...”。

因此,不可能在构造函数中定义常量吗?

由于常量的值取决于变量VARIANT,因此我做了一个 ifelse读取正确的.json文件的操作。

// constants.h
extern const int    BARL;
extern const int BAR_TOL;

// constants.cpp
Constants::Constants() {
    Json::Reader reader;
    Json::Value root;

    #if VARIANT == A
        std::ifstream config_a_file("a.json");
        reader.parse(config_a_file, root);
    #elif VARIANT == B
        std::ifstream config_b_file("b.json");
        reader.parse(config_b_file, root);
    #endif

    const int   BARL = root["BARL"].asInt();
    const int   BAR_TOL = BARL * 3;
}
Run Code Online (Sandbox Code Playgroud)

我想到的是,常量BARLBAR_TOL可以在整个constants.cpp类中使用。但是,找不到它们的定义。

Sto*_*ica 6

声明外部变量时,它们出现的作用域必须与名称空间定义的作用域匹配。而且,您根本无法在块作用域中定义两个具有外部链接的全局变量。

撇开关于为什么要谨慎使用此类全局常量的讨论1,我会说您正在犯错。由于您有一个Constants类,因此只需将这些常量公开为成员,然后声明一个外部Constants实例即可。就像是:

struct Constants {
    int    BARL;
    int BAR_TOL;
    Constants();
};

extern Constants const constants;
Run Code Online (Sandbox Code Playgroud)

然后其他代码可能会处理更好的命名空间constants.BARL,它本身是一个常量,因为它是const constants对象的子对象。

相应的cpp文件变为:

Constants const constants; // definition

Constants::Constants() {
    Json::Reader reader;
    Json::Value root;

    #if VARIANT == A
        std::ifstream config_a_file("a.json");
        reader.parse(config_a_file, root);
    #elif VARIANT == B
        std::ifstream config_b_file("b.json");
        reader.parse(config_b_file, root);
    #endif

    BARL = root["BARL"].asInt(); // assignment
    BAR_TOL = BARL * 3;
}
Run Code Online (Sandbox Code Playgroud)

1-为此,您可以浏览以获得许多示例,这些示例说明了为什么不同翻译单元中的静态变量之间未指定的初始化顺序会引起麻烦。