我想有一个类的私有静态常量(在这种情况下形状工厂)。我想有这样的事情。
class A {
private:
static const string RECTANGLE = "rectangle";
}
不幸的是,我得到了C ++(g ++)编译器的各种错误,例如:
ISO C ++禁止成员'RECTANGLE'的初始化
非整型类型“std :: string”的静态数据成员的无效类内初始化
错误:使“RECTANGLE”静态
在C ++ 11中,你现在可以做到:
class A {
private:
static constexpr const char* STRING = "some useful string constant";
};
你必须在类定义之外定义静态成员,并在其中提供初始化程序。
第一
// 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";
你最初尝试使用的语法(类定义中的初始值设定项)只允许使用整型和枚举类型。