我想声明将在项目中跨各种类使用的字符串常量。我正在考虑两种选择
选项 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/