如果我将 class 声明为 const...而不是 constexpr,程序将无法运行?

Program doesn't work if I declare class as const...rather than constexpr?

这是我的程序:

#include <iostream>

class Debug {
public:
    constexpr Debug(bool h): hw(h){}
    constexpr bool any() { return hw; }
private:
    bool hw;
};

int main(){

    const Debug x(true);

    constexpr bool f = x.any();

}

这会引发错误 "the value of 'x' is not usable in a constant expression"。如果我更换

const Debug x(true);

constexpr Debug x(true);

然后一切正常。我的印象是将 constexpr 放在对象定义与 "implicitly make this variable a const while verifying it is a constant expression variable" 同义的前面。这向我建议,在这个程序的情况下,使用 "const" 而不是 "constexpr" 应该没有什么不同。事实上,如果有什么地方出错了,它应该声明为 "constexpr",而不是 "const"。

抛开一切。我不明白 x 为什么不是常量表达式变量。 class Debug 满足文字 class 类型的条件,x 被声明为 const 并且它使用一个 constexpr 构造函数和一个作为常量表达式的初始化器。

编辑:这个程序启动了同样的错误(诚然,这应该是我原来的程序)。

using namespace std;

class Debug {
public:
    constexpr Debug(bool h): hw(h){}
private:
    bool hw;
};

int main(){
    const Debug x(true);
    constexpr Debug f = x;
}

constexpr 应用于函数意味着当且仅当函数的所有输入都是常量表达式时,函数的结果是常量表达式。在成员函数的情况下,输入是参数,以及调用它的对象。

所以只有当xconstexprx.any()才是常量表达式。如果只是 const,那么 x.any() 不是常量表达式。