如果我将类声明为常量,程序不起作用...而不是康特斯普?
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();
}
这引发了错误"'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
应用于函数意味着函数的结果是常量表达式,当且仅当函数的所有输入都是常量表达式。在成员函数的情况下,输入是参数和它所调用的对象
因此,只有当x
是constexpr
时,x.any()
才是常数表达式。如果它只是const
,那么x.any()
就不是一个常数表达式。
相关文章:
- 我的神经网络不起作用 [XOR 问题]
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- C++为什么尽管我调用了void函数,它却不起作用
- 为什么在保护模式下继承升级不起作用
- 循环在计数器中不起作用
- 在其他文件中创建类时在 c++ 项目中不起作用
- Visual studio代码重构似乎不起作用(例如,重命名符号-f2)
- 为什么二进制搜索在我的测试中不起作用
- 我的代码中有错误吗?使用BGI图形的C++代码对我不起作用
- C++:矩阵高斯消除不起作用:使用单维数组来存储元素
- 为什么这个斯芬娜不起作用
- 正在处理约瑟夫斯问题,节点函数不起作用
- 使用弗洛伊德-斯坦伯格抖动不起作用
- 斯坎f 输入不起作用
- 如果我将类声明为常量,程序不起作用...而不是康特斯普?
- 阿姆斯特朗数字的代码不起作用
- 当比较sizeof(type) == constant时,c++模板特化不起作用
- 为什么这个帕斯卡三角形程序不起作用?
- 当使用英特尔编译器和 -std=c++11 标志时,NVCC 不起作用