sto*_*one 27 c++ string static namespaces anonymous
我需要定义一些仅由一个类使用的常量字符串.看起来我有三个选择:
将字符串直接嵌入到使用它们的位置.
将它们定义为类的私有静态常量成员:
//A.h
class A {
private:
static const std::string f1;
static const std::string f2;
static const std::string f3;
};
//A.cpp
const std::string f1 = "filename1";
const std::string f2 = "filename2";
const std::string f3 = "filename3";
//strings are used in this file
Run Code Online (Sandbox Code Playgroud)在cpp文件中的匿名命名空间中定义它们:
//A.cpp
namespace {
const std::string f1 = "filename1";
const std::string f2 = "filename2";
const std::string f3 = "filename3";
}
//strings are used in this file
Run Code Online (Sandbox Code Playgroud)鉴于这些选项,您会推荐哪一个?为什么?谢谢.
如果它们仅在单个文件中使用,则不需要将它们包含在头文件中,从而将它们暴露给外界.
如果它们被使用并且将始终仅在一个地方使用,那么实际上没有理由不将它们写为需要使用它们的文字.
如果它们在cpp中的多个位置使用,我会选择匿名命名空间.
你没有提到的另一个选择是将它们定义为cpp中的静态变量.这有点等同于匿名命名空间选项,而且比C++更像C.