在 PHP 和 C # 中,常量可以在声明时初始化:
class Calendar3
{
const int value1 = 12;
const double value2 = 0.001;
}
下面是一个函数的 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;
};
这段代码的编译没有遇到 g + + 的问题,现在在 C + + 0x 模式(- std = c + + 0x)下,g + + 编译器输出一个错误消息:
错误: 类内初始化非整型静态数据成员“公差”所需的“ conconexpr”
我知道我可以在类定义之外定义和初始化这个 static const
成员。此外,可以在构造函数的初始化器列表中初始化非静态常数数据成员。
但是有没有什么方法可以像在 PHP 或 C # 中那样在类声明中初始化一个常量呢?
我使用 static
关键字仅仅是因为可以在 g + + 中的类声明中初始化这些常量。我只需要一种方法来初始化类声明中的常量,不管它是否声明为 static
。