静态常量字符串(类成员)

新手上路,请多包涵

我想要一个类的私有静态常量(在本例中是一个形状工厂)。

我想要那种东西。

 class A {
   private:
      static const string RECTANGLE = "rectangle";
}

不幸的是,我从 C++ (g++) 编译器中得到了各种错误,例如:

ISO C++ 禁止初始化成员“RECTANGLE”

非整数类型“std::string”的静态数据成员的类内初始化无效

错误:使“矩形”静态

这告诉我这种成员设计不符合标准。如何在不必使用#define 指令的情况下拥有私有文字常量(或者可能是公共的)(我想避免数据全局性的丑陋!)

任何帮助表示赞赏。

原文由 lb. 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.6k
2 个回答

您必须在类定义之外定义静态成员并在那里提供初始化程序。

第一的

// In a header file (if it is in a header file in your case)
class A {
private:
  static const string RECTANGLE;
};

接着

// In one of the implementation files
const string A::RECTANGLE = "rectangle";

您最初尝试使用的语法(类定义中的初始化程序)仅允许用于整数和枚举类型。


从 C++17 开始,您有另一个选项,它与您的原始声明非常相似:内联变量

// In a header file (if it is in a header file in your case)
class A {
private:
  inline static const string RECTANGLE = "rectangle";
};

不需要额外的定义。

原文由 AnT stands with Russia 发布,翻译遵循 CC BY-SA 4.0 许可协议

快进到 2018 年和 C++17。

  • 不要使用 std::string,使用 std::string_view 文字
  • 请注意下面的“constexpr”。这也是一种“编译时”机制。
  • 没有内联并不意味着重复
  • 为此不需要任何 cpp 文件
  • static_assert 仅在编译时“有效”
   using namespace std::literals;

  namespace STANDARD {
  constexpr
  inline
  auto
  compiletime_static_string_view_constant() {
  // make and return string view literal
  // will stay the same for the whole application lifetime
  // will exhibit standard and expected interface
  // will be usable at both
  // runtime and compile time
  // by value semantics implemented for you
      auto when_needed_ =  "compile time"sv;
      return when_needed_  ;
  }

};

以上是一个适当且合法的标准 C++ 公民。它可以很容易地参与任何和所有 std:: 算法、容器、实用程序等。例如:

 // test the resilience
auto return_by_val = []() {
    auto return_by_val = []() {
        auto return_by_val = []() {
            auto return_by_val = []() {
return STANDARD::compiletime_static_string_view_constant();
            };
            return return_by_val();
        };
        return return_by_val();
    };
    return return_by_val();
};

// actually a run time
_ASSERTE(return_by_val() == "compile time");

// compile time
static_assert(
   STANDARD::compiletime_static_string_view_constant()
   == "compile time"
 );

享受标准 C++

原文由 user10133158 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题