返回的对象如何可分配?
在 Effective C++ 第 3 条中,Scott Meyers 建议为名为 Rational
的类重载 operator*
:
In Effective C++, Item 3, Scott Meyers suggests overloading operator*
for a class named Rational
:
class Rational { ... };
const Rational operator*(const Rational& lhs, const Rational& rhs);
返回值是const
-qualified的原因解释如下:如果不是const
,程序员可以编写如下代码:
The reason for the return value being const
-qualified is explained in the following line: if it were not const
, programmers could write code such as:
(a * b) = c;
或者,更有可能:
if (a*b = c)
很公平.现在我很困惑,因为我认为函数的返回值(此处为 operator*)是一个右值,因此不可赋值.我认为它不可分配,因为如果我有:
Fair enough. Now I’m confused as I?thought that the return value of a function, here operator*, was a rvalue, therefore not assignable. I take it not being assignable because if I?had:
int foo();
foo() += 3;
使用 invalid lvalue in assignment
将无法编译.为什么这里不会发生?有人可以对此有所了解吗?
that would fail to compile with invalid lvalue in assignment
.
Why doesn’t that happen here? Can someone shed some light on this?
编辑:我在 Scott Meyers 的那个项目上看到了许多其他线程,但没有一个解决我在这里暴露的右值问题.
EDIT: I have seen many other threads on that very Item of Scott Meyers, but none tackled the rvalue problem I exposed here.
推荐答案
重点是对于类类型,a = b
只是 a.operator=(b) 的简写
,其中 operator=
是成员函数.并且可以在右值上调用成员函数.
The point is that for class types, a = b
is just a shorthand to a.operator=(b)
, where operator=
is a member function. And member functions can be called on rvalues.
请注意,在 C++11 中,您可以通过使 operator=
仅左值来禁止它:
Note that in C++11 you can inhibit that by making operator=
lvalue-only:
class Rational
{
public:
Rational& operator=(Rational const& other) &;
// ...
};
&
告诉编译器这个函数不能在右值上调用.
The &
tells the compiler that this function may not be called on rvalues.
相关文章