操作符过载,允许使用右值捕获,但不分配给 [英] Operator overload which permits capturing with rvalue but not assigning to

查看:104
本文介绍了操作符过载,允许使用右值捕获,但不分配给的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以设计,以及如何对我的类 C 进行重载 operator +

Is it possible to design and how should I make overloaded operator+ for my class C to have this possible:

C&& c = c1 + c2;

但不可能:

c1 + c2 = something;

编辑:
我将对象更改为小写字母。 c1 c2 c c $ c> C 。 &&& 不是逻辑运算符&& ,而是一个右值引用。

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.

例如:

double&& d = 1.0 + 2.0;

是100%正确的(新)C ++代码,而

is 100% proper (new) C++ code, while

1.0 + 2.0 = 4.0;

显然是一个编译器错误。我想要完全相同,而是双重,对于我的类 C

is obviously a compiler error. I want exactly the same, but instead for double, for my class C.

第二次编辑:
如果我的操作符返回C或C& amp;,我可以赋值为右值引用,但也赋值给c1 + c2,这是无意义的。 Giving const禁用它,但是它禁用赋值到右值。至少在VC ++ 2k10。

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?

推荐答案

赋值操作符只能在lvalue上调用:

Have the assignment operator be callable on lvalues only:

class C
{
    // ...

public:

    C& operator=(const C&) & = default;
};

请注意括号后的单个符号。它阻止分配到右值。

Note the single ampersand after the closing parenthesis. It prevents assigning to rvalues.

这篇关于操作符过载,允许使用右值捕获,但不分配给的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆