Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/143.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 程序不';如果我将类声明为const…而不是constexpr,它就不起作用了?_C++_Class_Constexpr - Fatal编程技术网

C++ 程序不';如果我将类声明为const…而不是constexpr,它就不起作用了?

C++ 程序不';如果我将类声明为const…而不是constexpr,它就不起作用了?,c++,class,constexpr,C++,Class,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(); } 与 然后一切正常。我的印象是,

这是我的节目:

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

}

然后一切正常。我的印象是,将constexpr放在对象定义之前与“隐式地将此变量设置为const,同时验证它是否为常量表达式变量”同义。这对我来说意味着在这个程序中使用“const”而不是“constexpr”应该没有什么不同。事实上,如果有任何东西出错,它应该将其声明为“constexpr”,而不是“const”

尽管如此。我不明白x为什么不是一个常量表达式变量。类调试满足文本类类型的条件,x被声明为const,并且它使用一个constexpr构造函数和一个常量表达式的初始化器

编辑:这个程序会出现同样的错误(无可否认,这应该是我的原始程序)


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


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

x
不是
constepr
,那么您希望如何在
constepr
中使用它呢huh@LightningRacisinObrit,@chris@LightningRacisinObrit,有趣的是,我不知道它在C++11中是隐式的。我只是想解释一下OP的逻辑。“如果它适用于
int
,为什么不是一个类?”我的问题来自于这样的想法:
constepr
const
没有任何不同,只是强制编译器验证变量是常量表达式。但是
constepr
实际上强制编译时初始化,而
const
则不强制编译时初始化。因此,正如您所说,对于我计划在常量表达式中使用的变量,我需要确保它们是用
constepr
限定符初始化的。而且,至关重要的是,由于C++14
constepr
成员函数不是隐式的
const
。这将是一个很好的最后一句话。
const Debug x(true);
constexpr Debug x(true);
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;
}