初始化constexpr静态类成员时的编译器错误 [英] Compiler error when initializing constexpr static class member
本文介绍了初始化constexpr静态类成员时的编译器错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经通过以下方式声明了一个类
I've declared a class in the following way
class A
{
struct B
{
constexpr
B(uint8_t _a, uint8_t _b) :
a(_a),
b(_b)
{}
bool operator==(const B& rhs) const
{
if((a == rhs.a)&&
(b == rhs.b))
{
return true;
}
return false;
}
uint8_t a;
uint8_t b;
};
constexpr static B b {B(0x00, 0x00)};
};
但是g ++表示
错误:字段初始值设定项不是常量
error: field initializer is not constant
无法弄清楚我错了。
推荐答案
C语更有用:
27 : error: constexpr variable 'b' must be initialized by a constant expression
constexpr static B b {B(0x00, 0x00)};
^~~~~~~~~~~~~~~~
27 : note: undefined constructor 'B' cannot be used in a constant expression
constexpr static B b {B(0x00, 0x00)};
^
8 : note: declared here
B(uint8_t _a, uint8_t _b) :
^
在成员变量的
brace-or-equal-initializer 中,构造函数(包括嵌套类的构造函数)被认为是未定义的;这是因为对于构造函数而言,引用成员变量的值是合法的,因此即使在词法上它们后来位于文件中,也必须首先定义成员变量:
Within a brace-or-equal-initializer of a member variable, constructors (including constructors of nested classes) are considered undefined; this is because it is legitimate for a constructor to refer to the values of member variables, so the member variables must be defined first even if they are lexically later in the file:
struct A {
struct B { int i; constexpr B(): i{j} {} };
constexpr static int j = 99;
};
解决方法是将 B
放在 A
,或者在基类中。
The workaround is to place B
outside A
, or perhaps within a base class.
这篇关于初始化constexpr静态类成员时的编译器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文