我想为类设置一个私有静态常量(在本例中是一个形状工厂)。
我想要类似的东西。
class A {
private:
static const string RECTANGLE = "rectangle";
}不幸的是,我从C++ (g++)编译器那里得到了各种各样的错误,例如:
C++禁止初始化成员‘矩形’ 非整数类型‘std::string’的静态数据成员的类内初始化无效 错误:使“矩形”静态
这告诉我,这种成员设计不符合标准。如何使用私有的文字常量(或者公共的)而不必使用#define指令(我希望避免数据全局性的丑陋!)
任何帮助都是非常感谢的。
发布于 2009-10-14 02:03:36
您必须在类定义之外定义静态成员,并在那里提供初始化器。
第一
// 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";
};不需要额外的定义。
发布于 2014-06-21 11:27:54
在C++11中,您现在可以这样做:
class A {
private:
static constexpr const char* STRING = "some useful string constant";
};发布于 2009-10-14 08:30:25
在类定义中,只能声明静态成员。它们必须在类之外定义。对于编译时积分常量,标准的例外情况是可以“初始化”成员。不过,这仍然不是一个定义。例如,在没有定义的情况下,获取地址是行不通的。
我想提到的是,对于常量,在const char[]上使用std::string是没有好处的。string很不错,但是它需要动态初始化。所以,如果你写的东西
const std::string foo = "hello";在命名空间范围内,foo的构造函数将在执行main启动之前运行,此构造函数将在堆内存中创建常量"hello“的副本。除非您真的需要矩形才能成为std::string,否则您也可以编写
// class definition with incomplete static member could be in a header file
class A {
static const char RECTANGLE[];
};
// this needs to be placed in a single translation unit only
const char A::RECTANGLE[] = "rectangle";那里!没有堆分配,没有复制,没有动态初始化。
干杯,s。
https://stackoverflow.com/questions/1563897
复制相似问题