在C++中,operator[]是一种重载运算符,用于访问类或数组对象中的元素。下面是operator[]的一些常见用法:
int arr[5] = {1, 2, 3, 4, 5};int element = arr[2]; // 获取数组arr中索引为2的元素,即3访问std::vector容器中的元素:#include <vector>std::vector<int> vec = {1, 2, 3, 4, 5};int element = vec[3]; // 获取vector vec中索引为3的元素,即4自定义类实现operator[]:class MyArray {private: int data[5] = {1, 2, 3, 4, 5};public: int& operator[](int index) { return data[index]; }};MyArray myArray;int element = myArray[2]; // 使用自定义类中的operator[]来访问元素注意:在自定义类中重载operator[]时,通常需要返回一个引用,以便可以修改该元素的值。


