c++ - 类中的静态字符串常量与常量的命名空间 [c++]

标签 c++ namespaces constants string-constant

我想声明将在项目中跨各种类使用的字符串常量。我正在考虑两种选择

选项 1:

#header file 
class constants{
    static const string const1;
};

#cpp file

const string constants::const1="blah";

选项 2:

#header file 
namespace constants{
    static const string const1="blah";
};

只是想知道什么是更好的实现。

已经看过了

Where to store Class Specific named constants in C++

Where to put constant strings in C++: static class members or anonymous namespaces


更新:

选项 3:

根据“potatoswatter”和“sellibitze”的建议,我目前有以下实现?

#header file
namespace constants{
    extern const string& const1(); //WORKS WITHOUT THE EXTERN  ***WHY***
};

#cpp file
namespace constants{
   const string& const1(){static string* str = new string ("blah"); return *str;}
}

我包含了我需要使用常量的头文件。这个实现有什么主要缺点吗?

最佳答案

2 年后更新:

每个可由多个源文件访问的全局变量都应包装在 inline 函数中,以便链接器在文件之间共享对象,并且程序会正确初始化它。

inline std::string const &const1() {
    static std::string ret = "hello, world!";
    return ret;
}

inline 函数是隐式的extern 并且可以包装在命名空间或类中,如果你愿意的话。 (但不要只使用类来保存静态成员,因为命名空间更适合。并且不要使用匿名命名空间,因为这会破坏链接器,并且每个源都会看到不同的 std::string 对象。)

关于c++ - 类中的静态字符串常量与常量的命名空间 [c++],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3670031/

相关文章:

php - Doctrine 2 实体中的常量

c++ - 多重指数实现

c++ - QUrl toPercentEncoding() 小写十六进制

c++ - cpp_dec_float_50 的精度是多少?

PHP 在删除自动加载器时 Composer 使工作失败

可以引用 php 常量但 defined() 返回 false

c++ - unique_ptr 和 shared_ptr 的区别

c# - 为什么我不能在对象初始化期间使用部分限定的 namespace ?

python - 如何将子模块导入父命名空间?

c++ - 仅为特定条件重置变量值,为其他一切设置固定值