【问题标题】:Compiler error when initializing constexpr static class member初始化 constexpr 静态类成员时出现编译器错误
【发布时间】:2014-07-02 09:23:28
【问题描述】:

我已经通过以下方式声明了一个类

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++ 说

错误:字段初始值设定项不是常量

不知道我错在哪里。

【问题讨论】:

  • @Manu343726 gcc (Debian 4.7.2-5) 4.7.2
  • 阅读this。我认为这是完全相同的问题。

标签: c++11 constexpr


【解决方案1】:

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) :
^

在成员变量的brace-or-equal-initializer中,构造函数(包括嵌套类的构造函数)被认为是未定义的;这是因为构造函数引用成员变量的值是合法的,所以必须先定义成员变量,即使它们在文件中的词法上是后面的:

struct A {
  struct B { int i; constexpr B(): i{j} {} };
  constexpr static int j = 99;
};

解决方法是将B 放在A 之外,或者可能放在基类中。

【讨论】:

    【解决方案2】:

    This will work:

    #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;
    }
    

    struct 中删除构造函数将允许大括号初始化程序工作。如果您打算在构造函数中做一些时髦的事情,这不会真正帮助您。

    【讨论】:

      猜你喜欢
      • 2012-07-16
      • 1970-01-01
      • 2021-08-07
      • 2013-10-19
      • 2016-10-15
      • 2018-11-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多