小编sto*_*one的帖子

我在C++中放置常量字符串:静态类成员还是匿名名称空间?

我需要定义一些仅由一个类使用的常量字符串.看起来我有三个选择:

  1. 将字符串直接嵌入到使用它们的位置.

  2. 将它们定义为类的私有静态常量成员:

    //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)
  3. 在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)

鉴于这些选项,您会推荐哪一个?为什么?谢谢.

c++ string static namespaces anonymous

27
推荐指数
2
解决办法
1万
查看次数

标签 统计

anonymous ×1

c++ ×1

namespaces ×1

static ×1

string ×1