常量引用与具体示例的混淆

const reference confusion with specific example

本文关键字:引用 常量      更新时间:2023-10-16

我有一个名为 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.这一点永远不会改变。你的作业不可能改变c2const性。

在赋值函数中,*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=,但实际上调用了复制构造函数(在这种情况下,这将是默认的构造函数,它只制作成员的浅拷贝)。