温馨提示×

c++中operator[]的使用方法

c++
小樊
94
2024-08-11 04:22:37
栏目: 编程语言

在C++中,operator[]是一种重载运算符,用于访问类或数组对象中的元素。下面是operator[]的一些常见用法:

  1. 访问数组元素:
int arr[5] = {1, 2, 3, 4, 5};
int element = arr[2]; // 获取数组arr中索引为2的元素,即3
  1. 访问std::vector容器中的元素:
#include <vector>
std::vector<int> vec = {1, 2, 3, 4, 5};
int element = vec[3]; // 获取vector vec中索引为3的元素,即4
  1. 自定义类实现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[]时,通常需要返回一个引用,以便可以修改该元素的值。

0