在C ++中的类声明中初始化const成员 [英] Initializing const member within class declaration in C++
问题描述
在PHP和C#中,常量可以在声明时初始化:
In PHP and C# the constants can be initialized as they are declared:
class Calendar3
{
const int value1 = 12;
const double value2 = 0.001;
}
我有一个函数的C ++声明,比较两个数学向量:
I have the following C++ declaration of a functor which is used with another class to compare two math vectors:
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 ++编译器输出一条错误信息:
This code compiled without problems with g++. Now in C++0x mode (-std=c++0x) the g++ compiler outputs an error message:
'
error: ‘constexpr’ needed for in-class initialization of static data member ‘tolerance’ of non-integral type
我知道我可以定义和初始化这个 static const
成员在类定义之外。另外,非静态常量数据成员可以在构造函数的初始化器列表中初始化。
I know I can define and initialize this static const
member outside of the class definition. Also, a non-static constant data member can be initialized in the initializer list of a constructor.
但是有什么方法可以在类声明中初始化一个常量
But is there any way to initialize a constant within class declaration just like it is possible in PHP or 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.
推荐答案
在C ++ 11中,非 - 静态
数据成员, static constexpr
数据成员,并且整数或枚举类型的 static const
数据成员可以在类声明中初始化。例如
In C++11, non-static
data members, static constexpr
data members, and static const
data members of integral or enumeration type may be initialized in the class declaration. e.g.
struct X {
int i=5;
const float f=3.12f;
static const int j=42;
static constexpr float g=9.5f;
};
在这种情况下, i
编译器生成的构造函数将 X
的所有实例初始化为 5
, f
成员初始化为 3.12
。 static const
数据成员 j
初始化为 42
并将 static constexpr
数据成员 g
初始化为 9.5
In this case, the i
member of all instances of class X
is initialized to 5
by the compiler-generated constructor, and the f
member is initialized to 3.12
. The static const
data member j
is initialized to 42
, and the static constexpr
data member g
is initialized to 9.5
.
由于 float
和 double
或枚举类型,这些成员必须是 constexpr
或非 - static
Since float
and double
are not of integral or enumeration type, such members must either be constexpr
, or non-static
in order for the initializer in the class definition to be permitted.
在C ++ 11之前,只有 static const
整数或枚举类型的数据成员才可以在类定义中有初始值。
Prior to C++11, only static const
data members of integral or enumeration type could have initializers in the class definition.
这篇关于在C ++中的类声明中初始化const成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!