在运算符重载中的使用 &
Use of & in operator overloading
我刚刚看到了这段代码:
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;
一样。
相关文章:
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- <T> 通过模板化运算符重载将 std::complex 乘以双倍
- C++20概念:需要运算符重载
- 使用赋值运算符重载从类中返回jobject
- 在运算符重载定义中使用成员函数(const错误)
- 字节到位运算符重载C++
- 为什么在运算符重载时需要参考?
- 类中 c++ 的运算符 + 重载
- 算术复合运算符重载为非成员
- 运算符重载 (+),用于添加两个具有 C++ 的数组
- 交换运算符 + 重载会导致无限递归
- 如何理解新的运算符重载?
- 向量保持复数的运算符重载
- 如何创建运算符重载?
- 链接列表运算符重载没有打印出我想要的内容
- C++:需要帮助了解运算符重载错误
- 使用模板化运算符重载 XOR 运算符失败
- 如何确保接受的C++模板类型使运算符重载?
- 运算符重载使用运算符+添加类模板