常量引用与具体示例的混淆
const reference confusion with specific example
我有一个名为 counter 的类,我的赋值运算符如下所示:
const counter& counter::operator=(const counter& y)
{
count = y.count;
return *this;
}
现在,我的困惑源于返回值:
const counter& counter:: ...
我认为这意味着计数器的赋值运算符应该返回一个常量计数器引用,并且由于它是常量,该对象应该是不可变的,但据我所知,它不是。
这是我的反测试代码,我已经在我的担忧中发表了评论:
#include "counter.h"
#include <iostream>
using std::cout;
using std::endl;
int main()
{
counter c; // c.count = 0
c.Inc(); // c.count = 1
c.Inc(); // c.count = 2
counter c2;
// Here I use my assignment operator so shouldn't c2 be immutable?
c2 = c; // c3.count = 2
// Why does this work?
c2.Inc(); // c3.count = 3
c2.Inc(); // c3.count = 4
cout << "c = " << c.Count() << ", c2 = " << c2.Count()
<< endl; // prints: c = 2, c2 = 4
}
这是你声明c2
的方式:
counter c2;
如您所见,这不是const
.这一点永远不会改变。你的作业不可能改变c2
的const
性。
在赋值函数中,*this
是指要赋值的对象,而不是返回值。返回值是表达式 c2 = c
的值。因此,如果您尝试修改结果,也许使用 (c2 = c).Inc()
,它将不起作用,因为返回值为 const
.
我注意到您似乎认为const counter& counter::
是函数的返回类型。实际上,只是const counter&
。counter::
部分是一个嵌套的名称说明符,表示 operator=
函数是 counter
类的成员。
const counter& counter::operator=(const counter& y)
^^^^^^^^^^^^^^ ^^^^^^^^ ^^^^^^^^^ ^^^^^^^^^^^^^^^^
return type scope func name parameters
const counter& counter::operator=(const counter& y)
您只需更改标准operator=
的含义,该将被定义为counter& counter::operator=(const counter& y)
,您无法以这种特殊形式连接它:(a=b)=c
.或者也不是(a=b).Inc()
.但是正常的a=b=c
是可能的。
任何运算符之前,必须将变量显式定义为const
。它不能在它之后得到const
,具体取决于返回类型。因此,如前所述,您需要将 c2 定义为 const。
编辑:
此外,您还应该考虑编写自己的复制构造函数,因为const c2 = c
看起来只是调用了operator=
,但实际上调用了复制构造函数(在这种情况下,这将是默认的构造函数,它只制作成员的浅拷贝)。
- 什么时候在C++中返回常量引用是个好主意
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 为什么我可以通过引用修改常量返回
- 返回常量对象引用 (getter) 和仅返回字符串有什么区别?
- 将常量指针引用绑定到非常量指针
- 通过常量引用传递参数的矩阵模板类
- 按值捕获引用时出现非常量
- 在C++中使用非常量引用作为常量
- 具有常量引用参数的函数模板专用化
- 多个"常量引用"变量可以共享同一个内存吗?
- 为什么 STL 容器适配器堆栈中的 top 返回常量引用?
- 为什么按值传递QStringView比引用常量更快?
- 通过引用常量函数调用另一个类的非常量函数
- 构造常量对象与引用常量对象
- 引用“常量value_type”时出错
- 为什么可以在 for 语句中重新分配引用常量
- 程序反馈:命名循环索引和引用常量数据
- 堆还是栈?在c++中函数调用中引用常量字符串时
- 为什么常量结构数组在按名称引用常量结构时不放在 .rodata 中?
- 为什么编译器允许在函数中发送对迭代器的引用,该函数引用常量迭代器