How can a returned object be assignable?(返回的对象如何可分配?)
问题描述
在 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.
这篇关于返回的对象如何可分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:返回的对象如何可分配?
- 从父 CMakeLists.txt 覆盖 CMake 中的默认选项(...)值 2021-01-01
- 如何提取 __VA_ARGS__? 2022-01-01
- 将函数的返回值分配给引用 C++? 2022-01-01
- DoEvents 等效于 C++? 2021-01-01
- OpenGL 对象的 RAII 包装器 2021-01-01
- 将 hdc 内容复制到位图 2022-09-04
- GDB 不显示函数名 2022-01-01
- 哪个更快:if (bool) 或 if(int)? 2022-01-01
- 使用 __stdcall & 调用 DLLVS2013 中的 GetProcAddress() 2021-01-01
- XML Schema 到 C++ 类 2022-01-01
