所以在我的C ++作业中,指令说..
为kUnboundLower和kUnboundUpper创建一个constexpr成员。
...
创建下限和上限设置器和getter。
这怎么可能?如果有什么东西是constexpr
你不能再设置它。我在这里错过了什么?
如果有什么东西是constexpr你不能再设置它。我在这里错过了什么?
您可以在constexpr上下文中修改对象,但前提是修改是constexpr。
例如:
constexpr auto foo() -> int { return 24; }
struct X
{
int x_;
constexpr auto x() -> int& { return x_; }
};
constexpr auto make_x(int a)
{
X x{};
x.x() = a; // invalid if `x()` is not `constexpr`
return x;
}
auto test()
{
constexpr auto x = make_x(24);
}
请想象一个更实用的例子,这是有用的,我的大脑现在太累了想出一个实际的例子,但是有,例如当你不能从构造函数创建对象,但需要单独设置成员创作之后。
这怎么可能?如果有什么东西是constexpr你不能再设置它。我在这里错过了什么?
不确定,但在我看来你误解了你的任务。
创建一个接受:[下限,上限]的ctor。
您的类定义一个范围,具有下限和上限;你必须创建一个构造函数,它接收下限值和上限值。
创建一个在上限和下限值上都未绑定的默认ctor。
默认构造函数是不接收任何参数的构造函数。如果我理解正确,默认构造函数必须为与未绑定值对应的上限和下限设置特殊值
为kUnboundLower和kUnboundUpper创建一个constexpr成员。
不确定,但我认为kUnboudLower
和kUnboundUpper
是下限和上限的特殊未绑定值;他们是constexpr
所以他们是static
。
例如,某事如
#include <limits> // for std::numeric_limits
class range
{
private:
static constexpr int kUnboundLower { std::numeric_limits<int>::min() };
static constexpr int kUnboundUpper { std::numeric_limits<int>::max() };
int lBound;
int uBound;
public:
// default constructor
range () : lBound{kUnboundLower}, uBound{kUnboundUpper}
{ }
// constructor with values
range (int l, int u) : lBound{l}, uBound{u}
{ }
// ......
};