在 C++ 中的类声明中初始化 const 成员

2022-01-23 00:00:00 g++ 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:

错误:类内初始化非整数类型的静态数据成员tolerance"需要constexpr"

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.

但是有什么方法可以在类声明中初始化一个常量,就像在 PHP 或 C# 中一样?

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 数据成员,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;
};

在这种情况下,类 X 的所有实例的 i 成员被编译器生成的构造函数初始化为 5,并且f 成员被初始化为 3.12.static const 数据成员 j 初始化为 42static 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.

由于 floatdouble 不是整数或枚举类型,因此此类成员必须是 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.

相关文章