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

C++类通用字符串常量

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

    #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;}
    

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

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

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

        2
  •  2
  •   Jem    16 年前

    当我需要类中的字符串常量时,我从不把它们放在类本身中,而是:

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

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

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

    然后,您甚至可以将来自同一头文件中几个相关组件的字符串常量分组。

        3
  •  0
  •   TimW    16 年前

    我永远不会使用这种结构。

       // 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,因为在使用partOfTheString创建整个String之前,没有必要对其进行初始化;

    如果我想创建类公共字符串,我可以这样做:

    // 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    16 年前

    根据 Wikipedia article 这应该得到支持 C++0x State of C++ Evolution 页面。