运算符重载允许使用右值捕获但不能分配给
是否可以设计以及如何为我的类 C
重载 operator+
来实现这一点:
C&& c = c1 + c2;
但这不可能:
c1 + c2 = something;
编辑: 我把物体改成了小写字母。 c1
、c2
和 c
是类 C
的对象。 &&
不是逻辑运算符&&,而是右值引用。
例如,写:
double&& d = 1.0 + 2.0;
是 100% 正确的(新)C++ 代码,而
1.0 + 2.0 = 4.0;
显然是编译器错误。我想要完全相同,但对于我的类C
来说是双倍的。
第二次编辑: 如果我的运算符返回 C 或 C&,我可以分配给右值引用,但也可以分配给 c1 + c2,这是毫无意义的。在这里给出 const 会禁用它,但它也会禁用对右值的分配。至少在 VC++ 2k10 上是这样。那么这有多少倍呢?
Is it possible to design and how should I make overloaded operator+
for my class C
to have this possible:
C&& c = c1 + c2;
but this not possible:
c1 + c2 = something;
Edit:
I changed objects to small letters. c1
, c2
and c
are objects of class C
. &&
is not the logical operator&&
, but rather an rvalue reference.
For example writing:
double&& d = 1.0 + 2.0;
is 100% proper (new) C++ code, while
1.0 + 2.0 = 4.0;
is obviously a compiler error. I want exactly the same, but instead for double, for my class C
.
Second edit:
If my operator returns C or C&, I can have assignment to rvalue reference, but also assignment to c1 + c2, which is senseless. Giving const here disables it, however it disables assignment to rvalue too. At least on VC++ 2k10. So how double does this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
让赋值运算符只能在左值上调用:
请注意右括号后面的单个 & 符号。它阻止分配给右值。
Have the assignment operator be callable on lvalues only:
Note the single ampersand after the closing parenthesis. It prevents assigning to rvalues.