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.
这篇关于返回的对象如何可分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:返回的对象如何可分配?


基础教程推荐
- C++,'if' 表达式中的变量声明 2021-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 设计字符串本地化的最佳方法 2022-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01