c++ - 构造函数声明为 constexpr
问题描述
我尝试了 IBM 知识中心的示例:我在 Visual Studio 2019 中运行它,它看起来不同:尽管有构造函数,但constexpr
我可以根据构造函数输入参数初始化成员D3
。以及在构造函数主体中,我可以为D3
. 这种差异的原因是什么?哪个构造函数定义为 constexpr ?
struct BASE {
};
struct B2 {
int i;
};
struct D1 : public BASE {
//OK, the implicit default constructor of BASE is a constexpr constructor.
constexpr D1() : BASE(), mem(55) { }
//OK, the implicit copy constructor of BASE is a constexpr constructor.
constexpr D1(const D1& d) : BASE(d), mem(55) { }
//OK, all reference types are literal types.
constexpr D1(NL &n) : BASE(), mem(55) { }
//The conversion operator is not constexpr.
operator int() const { return 55; }
private:
int mem;
};
struct D3 : B2 {
//error, D3 must not be a function try block.
constexpr D3(int) try : B2(), mem(55) { } catch(int) { }
//error, illegal statement is in body.
constexpr D3(char) : B2(), mem(55) { mem = 55; }
//error, initializer for mem is not a constant expression.
constexpr D3(double i) : B2(), mem(i) { }
//error, implicit conversion is not constexpr.
constexpr D3(const D1 &d) : B2(), mem(d) { }
//error, parameter NL is a non-literal type.
constexpr D3(NL) : B2(), mem(55) { }
private:
int mem;
};
解决方案
推荐阅读
- c# - 在委托操作中标签不显示
- excel - 复制一堆工作表并使用原始工作表的范围保存?
- palantir-foundry - 从 Slate 主页删除/隐藏“操作”按钮
- python - 为什么我不能使用 Discord.py 禁止/踢人?
- php - 从数组PHP中搜索数组的第一个数组中获取密钥
- laravel - Problem with laravel/ui in laravel after the last update
- javascript - 有没有办法在视觉上重新格式化这段代码?为什么会这样?
- ios - 如何在 SwiftUI 中访问“发送者”的手势?
- mysql - 在 MySQL 中加入表的转置
- omnet++ - OMNeT++ 批量执行弄乱了结果