【发布时间】:2012-02-26 20:32:33
【问题描述】:
在 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++ 编译器会输出错误消息:
错误:类内初始化非整数类型的静态数据成员“tolerance”需要“constexpr”
我知道我可以在类定义之外定义和初始化这个static const 成员。此外,可以在构造函数的初始化列表中初始化非静态常量数据成员。
但是有什么方法可以在类声明中初始化一个常量,就像在 PHP 或 C# 中一样?
更新
我使用 static 关键字只是因为可以在 g++ 的类声明中初始化这些常量。我只需要一种方法来初始化类声明中的常量,无论它是否声明为static。
【问题讨论】:
-
I used static keyword just because it was possible to initialize such constants within the class declaration in g++. I just need a way to initialize a constant in a class declaration no matter if it declared as static or not.这是决定成员是否应为static的错误方式。永远不要让词汇惰性决定代码的语义。 -
That's the wrong way to decide whether a member should be static or not.我不同意。我认为这对于固定成员来说并不重要。 -
@expresso:一点也不。您可以使用特定于实例的信息初始化非
static常量成员。你已经决定你的常量是类型的属性而不是特定实例的属性是使它成为static的原因,而不是因为你喜欢打字快捷方式。 -
@lightless:嗯,这是可能的,但我看不出有任何理由使用具有不同值的相同实例特定常量的初始化。我曾经为此使用非常量类字段!
-
为什么,如果它们在对象实例化后从未改变?
struct myType { const std::time_t instantiated; myType() : instantiated(std::time(0)) {} };所有可以是const应该是const;这适用于static和非static成员。