如何可以分配返回的对象? [英] How can a returned object be assignable?
问题描述
在Effective C ++中,项目3,Scott Meyers建议为 Rational
:重载 operator *
p>
class Rational {...};
const Rational运算符*(const Rational& lhs,const Rational& rhs);
返回值的原因是 const
-qualified解释如下:如果不是 const
,程序员可以编写如下代码:
(a * b)= c;
或更可能:
if(a * b = c)
现在我很困惑,因为我认为函数的返回值,这里是operator *,是一个右值,因此不可分配。我认为它不可分配,因为如果我有:
int foo();
foo()+ = 3;
无法编译赋值中的无效左值
。
为什么不会发生这里?
关于类类型, a = b
只是
a.operator =(b)
的简写,其中 operator =
功能。
请注意,在C ++ 11中,你可以通过 operator =
lvalue-only:
class Rational
{
public:
Rational& operator =(Rational const& other)& ;;
// ...
};
&
告诉编译器函数不能在右值上调用。
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);
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;
or, more probably:
if (a*b = c)
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;
that would fail to compile with invalid lvalue in assignment
.
Why doesn’t that happen here? Can someone shed some light on this?
EDIT: I have seen many other threads on that very Item of Scott Meyers, but none tackled the rvalue problem I exposed here.
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.
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.
这篇关于如何可以分配返回的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!