类vs命名空间中的静态字符串常量[c ++] [英] static string constants in class vs namespace for constants [c++]
问题描述
我要声明在项目中跨各种类使用的字符串常量。我正在考虑两个备选方案
I want to declare string constants that will be used across various classes in the project. I am considering two alternatives
选项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";
};
只是想知道什么是更好的实现。
Just wondering what would be a better implementation.
已查看
http://stackoverflow.com/questions/3299765/where-to-store-class-specific-named-constants-in-c
UPDATE:
UPDATE:
选项3 :
根据potatoswatter和sellibitze的建议,我目前有以下实现?
Based on the suggestions from "potatoswatter" and "sellibitze" i currently have the following implementation?
#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;}
}
我包含头文件,使用常量。
I'm including the header file where i need to use the constants. Are there any major cons of this implementation?
推荐答案
2年后更新:
每个可由多个源文件访问的全局应该被包含在 inline
函数中,因此链接器共享文件之间的对象,并且程序会正确初始化。
Every global accessible by more than one source file should be wrapped in an inline
function so the linker shares the object between the files, and the program initializes it properly.
inline std::string const &const1 {
static std::string ret = "hello, world!";
return ret;
}
inline
函数是隐式的 extern
,并且可以包装在命名的命名空间或类中,如果你喜欢。 (但不要使用类来保存静态成员,因为命名空间会更好,不要使用匿名的命名空间,因为它会破坏链接器,每个源都会看到不同的 std :: string
object。)
The inline
function is implicitly extern
and may be wrapped in a named namespace or a class, if you like. (But don't use a class just to hold static members, as namespaces are better for that. And don't use an anonymous namespace as that would defeat the linker, and each source would see a different std::string
object.)
这篇关于类vs命名空间中的静态字符串常量[c ++]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!