我以下列方式宣布了一堂课
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)};
};
Run Code Online (Sandbox Code Playgroud)
但是g ++说
错误:字段初始值设定项不是常量
无法弄清楚我错在哪里.
将不胜感激任何帮助!
谢谢和reagards!
eca*_*mur 10
Clang更有帮助:
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) :
^
Run Code Online (Sandbox Code Playgroud)
在成员变量的大括号或大小写初始化程序中,构造函数(包括嵌套类的构造函数)被认为是未定义的; 这是因为构造函数引用成员变量的值是合法的,因此必须首先定义成员变量,即使它们在文件中稍后有词法:
struct A {
struct B { int i; constexpr B(): i{j} {} };
constexpr static int j = 99;
};
Run Code Online (Sandbox Code Playgroud)
解决方法是放置B在外部A,或者可能放在基类中.
#include <cstdint>
#include <iostream>
class A
{
struct B
{
bool operator==(const B& rhs) const
{
if((a == rhs.a)&&
(b == rhs.b))
{
return true;
}
return false;
}
uint8_t a;
uint8_t b;
};
public:
constexpr static B b {0x61, 0x62};
};
int main() {
std::cout << '{' << A::b.a << ',' << A::b.b << '}' << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
从 中删除构造函数struct将允许大括号初始值设定项工作。如果您打算在构造函数中做一些时髦的事情,这不会真正帮助您。
| 归档时间: |
|
| 查看次数: |
629 次 |
| 最近记录: |