【问题标题】:define static string variable in c++ class在 C++ 类中定义静态字符串变量
【发布时间】:2012-02-29 10:09:32
【问题描述】:

我有两个问题:

为什么这对于 int 变量是可能的:

foo.h:

class foo{

     private:
        const static int a = 42;
};

但是对于字符串变量我需要这样做吗?

foo.h:

class foo{

     private:
        static string fooString;
};

foo.cpp:

string foo::fooString = "foo";

还有:

在我的特殊情况下 foo::fooString 应该代表一个路径变量,我希望对于 foo 类的每个对象只有一个 foo::string 实例,代表一个永远不会改变的 const 值。

还有其他方法可以解决这个问题吗?

【问题讨论】:

    标签: c++ string static


    【解决方案1】:

    为什么对于 int 变量可以这样做:[..] 但对于字符串变量我需要这样做?

    只是因为。实际上你仍然可以创建 string const 但是,是的,你必须在类定义之外define它。您只能在 static 成员为 const 和整数(或“文字类型”)时进行就地初始化。

    (在 C++11 中,当非static 非const 成员为文字类型时,您甚至可以这样做。)

    我希望类 foo 的每个对象都只有一个 foo::string 实例,代表一个永远不会改变的 const 值。有没有其他方法可以解决这个问题?

    如您所料,static const std::string。

    // C++03
    struct T {
       static const std::string foo;
    };
    
    const std::string T::foo = "lol";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-30
      • 2013-09-07
      • 2016-06-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多