提问人:jesses 提问时间:3/25/2021 最后编辑:jesses 更新时间:3/25/2021 访问量:74
使用用户定义的前缀和后缀递增运算符对类型进行 ++o++ 抱怨
Make ++o++ complain for types with user defined pre- and postfix increment operators
问:
我正在寻找一种方法来防止使用具有用户定义的前缀和后缀增量运算符的类型。++x++
对于内置类型,后缀运算符的结果类型不是左值,而是 prvalue 表达式,编译器很好地抱怨。
我能想到的最简单的事情是返回后缀增量运算符的 const:
struct S {
int i_;
S& operator++() {
++i_;
return *this;
}
S /*const*/ operator++(int) {
S result(*this);
++(*this);
return result;
}
};
int main() {
S s2{0};
++s2++;
}
这种方法有缺陷吗?
编辑:
多亏了答案,我在这里、这里,当然还有 cppreference 上找到了更多信息。
答:
4赞
Mooing Duck
3/25/2021
#1
你可能想要和.你错过了最后的,这使得运算符只对左值起作用。S& operator++() &
S operator++(int) &
&
2赞
Drew Dormann
3/25/2021
#2
您希望使前缀运算符仅适用于左值。++
此语法从 C++11 开始工作。
S& operator++() & {
// ^ This & allows only lvalues for *this
++i_;
return *this;
}
评论
0赞
jesses
3/25/2021
我接受了 Mooing Ducks 的回答,因为他的回答更快一些,并提到将 & 应用于前缀和后缀增量运算符。另一方面,我喜欢在你的回答中额外提到历史。
评论