我想为一个类(在这种情况下是一个形状工厂)有一个私有静态常量.
我想要有类似的东西.
class A {
private:
static const string RECTANGLE = "rectangle";
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,我从C++(g ++)编译器中得到了各种错误,例如:
ISO C++禁止成员'RECTANGLE'的初始化
非整数类型'std :: string'的静态数据成员的无效类初始化
错误:使'RECTANGLE'静止
这告诉我这种成员设计不符合标准.如何在不使用#define指令的情况下拥有私有文字常量(或者可能是公共的)(我想避免数据全局性的丑陋!)
任何帮助表示赞赏.
在PHP和C#中,常量可以在声明时初始化:
class Calendar3
{
const int value1 = 12;
const double value2 = 0.001;
}
Run Code Online (Sandbox Code Playgroud)
我有一个仿函数的以下C++声明,它与另一个类一起使用来比较两个数学向量:
struct equal_vec
{
bool operator() (const Vector3D& a, const Vector3D& b) const
{
Vector3D dist = b - a;
return ( dist.length2() <= tolerance );
}
static const float tolerance = 0.001;
};
Run Code Online (Sandbox Code Playgroud)
这个代码编译没有问题与g ++.现在在C++ 0x模式(-std = c ++ 0x)中,g ++编译器输出一条错误消息:
错误:'constexpr'需要对非整数类型的静态数据成员'容差'进行类内初始化
我知道我可以static const在类定义之外定义和初始化该成员.此外,可以在构造函数的初始化列表中初始化非静态常量数据成员.
但有没有办法在类声明中初始化一个常量,就像在PHP或C#中可能的那样?
我使用static关键字只是因为可以在g ++中的类声明中初始化这些常量.我只需要一种方法来初始化类声明中的常量,无论它是否声明static.
我正在尝试通过KIT 编译Contraction Hierarchies Implementation.
该软件已于2009年发布,从那以后显然没有得到维护.由于一些事情在平均时间内发生了变化(使用新的C++标准和编译器版本),代码不再编译.
在编写指令时,README并不是非常冗长,并且说你应该只调用它make.但是,使用make会给我以下错误:
g++ -Wall -W -Wno-unused-parameter -O6 -c -o main.o main.cpp
In file included from /usr/include/c++/4.8/ext/hash_map:60:0,
from command/../io/../datastr/graph/../../io/serialize.h:26,
from command/../io/../datastr/graph/edge.h:26,
from command/../io/../datastr/graph/graph.h:59,
from command/../io/createGraph.h:28,
from command/NodeOrder.h:29,
from main.cpp:35:
/usr/include/c++/4.8/backward/backward_warning.h:32:2: warning: #warning This file includes at least one deprecated or antiquated header which may be removed without further notice at a future date. Please use a non-deprecated interface with equivalent functionality instead. For a listing of replacement headers and interfaces, consult the file …