如何使用c++的operator[]

avatar
作者
猴君
阅读量:0

在 C++ 中,operator[] 是用于访问数组、容器和类中的元素的重载运算符。您可以通过使用方括号操作符 [] 来访问数组和容器中的元素,例如:

#include <iostream> #include <vector>  int main() {     int arr[5] = {1, 2, 3, 4, 5};          // 访问数组元素     std::cout << arr[2] << std::endl;  // 输出:3          std::vector<int> vec = {10, 20, 30, 40, 50};          // 访问向量元素     std::cout << vec[3] << std::endl;  // 输出:40          return 0; } 

除了数组和容器,您还可以在自定义类中重载 operator[] 来实现对类对象的元素访问。下面是一个示例:

#include <iostream>  class MyArray { private:     int data[5] = {1, 2, 3, 4, 5}; public:     int& operator[](int index) {         return data[index];     } };  int main() {     MyArray myArr;          // 访问自定义类中的元素     std::cout << myArr[2] << std::endl;  // 输出:3          return 0; } 

在上面的示例中,我们创建了一个自定义类 MyArray,并重载了 operator[] 运算符,以便我们可以像访问数组一样访问该类中的元素。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!