在运算符重载中的使用 &

Use of & in operator overloading

本文关键字:运算符 重载      更新时间:2023-10-16

我刚刚看到了这段代码:

float& operator [] (int);

想知道为什么我应该使用它 &,一旦有一些重载器不使用它。谢谢!

float& operator [] (int)提供对对象内部数据的索引读/写访问。 数据通过引用返回,因此调用方可以为其赋值,例如:

class myClass {
private:
    float arr[10];
public:
    float& operator[](int index) { return arr[index]; }
};
myClass m;
float f = m[index];
m[index] = 123.45; // m.arr updated!

另一方面,float operator [] (int)提供对对象数据的索引只读访问。数据按值返回,因此调用方接收数据的副本,并且无法将值赋回对象内的数据。

class myClass {
private:
    float arr[10];
public:
    float operator[](int index) const { return arr[index]; }
};
myClass m;
float f = m[index];
m[index] = 123.45; // m.arr not updated!

您必须考虑如何使用运算符。以std::vector为例。它可能(撇开实现细节不谈)实现其operator[]函数,如下所示:

T & operator[](size_t index) {
    return *(__internal_heap_allocated_array_ptr + index);
}

这样当你调用my_array[4] = 7 时,它返回索引 4 的实际物理位置,允许你为其赋值。

现在想象一下,如果这样写会发生什么:

T operator[](size_t index) {
    return *(__internal_heap_allocated_array_ptr + index);
}

如果您尝试执行相同的代码,my_array[4] = 7 ,则会出现编译错误,并且有充分的理由:您正在尝试为您访问的值的副本分配一个值,这在 C++ 中是不允许的(您不能将值分配给纯右值),即使允许,它也不会更改数组本身中的值。

此运算符通过引用返回 ( & ),以便您可以通过赋值更改值,就像 object[0] = obj.data; 一样。