代码之家  ›  专栏  ›  技术社区  ›  CW Holeman II

C++类常用字符串常量

  •  2
  • CW Holeman II  · 技术社区  · 15 年前

    在C++中,我想定义一些在类中使用的字符串,但是这些值在所有实例中都是通用的。在C中,我会使用 #define s下面是一个尝试:

    #include <string>
    class AskBase {
    public:
        AskBase(){}
    private:
        static std::string const c_REQ_ROOT = "^Z";
        static std::string const c_REQ_PREVIOUS = "^";
        static std::string const c_REQ_VERSION = "?v";
        static std::string const c_REQ_HELP = "?";
        static std::string const c_HELP_MSG = "  ? - Help\n ?v - Version\n ^^ - Root\n  ^ - Previous\n ^Z - Exit";
    };
    int main(){AskBase a,b;}
    

    如果需要C++0x,这是可以接受的。

    4 回复  |  直到 15 年前
        1
  •  10
  •   coppro    15 年前

    您必须在单个翻译单元(源文件)中单独定义它们,如下所示:

    //header
    class SomeClass
    {
      static const std::string someString;
    };
    
    //source
    const std::string SomeClass::someString = "value";
    

    我相信新的C++1x标准会解决这个问题,尽管我不能完全确定。

        2
  •  2
  •   Jem    15 年前

    1) 如果需要在标头中公开它们,我会将它们放在类之外(如果合适,放在命名空间中),如下所示:

    const char * const c_REQ_ROOT = "^Z";
    ...
    

    2) 如果没有,我将它们放在cpp文件中的匿名名称空间中。

    这可能不是最“学术”的方式,但代码更简单,更容易重构。我从未发现将字符串常量定义为静态类成员的任何实际优势。

        3
  •  0
  •   TimW    15 年前

    我永远不会使用那种结构。
    如果某个开发人员重构代码并开始编写:

       // header
       class StringBug
       {
            static const std::string partOfTheString;
            static const std::string wholeString;
       };
    
       // source
       const std::string StringBug::partOfTheString = "Begin ";
       const std::string StringBug::wholeString = partOfTheString + "and the rest";
    

    您在程序中有一个很难找到的bug,因为无法保证PartOfString在用于创建整体字符串之前已初始化;

    // header
    class StringBug
    {
        static const std::string& partOfTheString() {
           static const std::string sPartOfTheString("Begin ");
           return sPartOfTheString;      
        }
    
        static const std::string& wholeString() {
           static const std::string sWholeString( partOfTheString() + "and the rest");
           return sWholeString;
        }
    };
    
        4
  •  0
  •   Motti    15 年前

    根据 Wikipedia article 这一点应在以下方面得到支持: C++0x 但是,我在目录中找不到参考资料 State of C++ Evolution