如果我将类声明为常量,程序不起作用...而不是康特斯普?

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

本文关键字:不起作用 康特斯 程序 声明 常量 如果      更新时间:2023-10-16

这是我的程序:

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

这引发了错误"'x'的值在常量表达式中不可用"。如果我更换

const Debug x(true);

带有

constexpr Debug x(true);

然后一切都很好。我的印象是,在对象定义之前放constexpr与"在验证此变量是常量表达式变量时隐式地将其设为const"同义。这对我来说意味着,在这个程序的情况下,用"const"代替"constexpr"应该没有什么不同。事实上,如果有任何错误,应该将其声明为"constexpr",而不是"const"。

不过,一切都放在一边。我不明白x怎么不是一个常量表达式变量。类Debug满足文字类类型的标准,x被声明为const,并且它使用带有作为常量表达式的initializers的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应用于函数意味着函数的结果是常量表达式,当且仅当函数的所有输入都是常量表达式。在成员函数的情况下,输入是参数和它所调用的对象

因此,只有当xconstexpr时,x.any()才是常数表达式。如果它只是const,那么x.any()就不是一个常数表达式。