温馨提示×

c++ operator[] 怎样实现

c++
小樊
131
2024-12-02 15:47:49
栏目: 编程语言

在 C++ 中,operator[] 是一个重载的下标运算符,它允许你通过数组或类似的容器类型的对象来访问其元素。要实现一个类的 operator[],你需要遵循以下步骤:

  1. 返回一个引用:为了允许通过下标访问元素,你需要返回一个对容器内元素的引用。这样,你可以通过这个引用来修改元素。
class MyArray {
public:
    int& operator[](int index) {
        // 实现细节
    }
};
  1. 检查边界:为了防止访问越界,你需要检查给定的索引是否在容器的有效范围内。如果索引越界,你可以选择抛出异常或者返回一个默认值。
int& operator[](int index) {
    if (index < 0 || index >= size) {
        throw std::out_of_range("Index out of range");
    }
    return data[index];
}
  1. 实现细节:在实现中,你需要根据你的容器类型(如数组、向量等)来存储数据,并确保在访问元素时不会越界。

下面是一个简单的 MyArray 类示例,它使用动态数组来存储数据:

#include <iostream>
#include <stdexcept>

class MyArray {
public:
    MyArray(int size) : size(size), data(new int[size]) {}

    ~MyArray() {
        delete[] data;
    }

    int& operator[](int index) {
        if (index < 0 || index >= size) {
            throw std::out_of_range("Index out of range");
        }
        return data[index];
    }

private:
    int size;
    int* data;
};

int main() {
    MyArray arr(5);
    arr[0] = 1;
    arr[1] = 2;
    arr[2] = 3;
    arr[3] = 4;
    arr[4] = 5;

    try {
        std::cout << "arr[0]: " << arr[0] << std::endl;
        std::cout << "arr[5]: " << arr[5] << std::endl;
    } catch (const std::out_of_range& e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }

    return 0;
}

这个示例中的 MyArray 类使用动态数组来存储数据,并在访问元素时检查边界。如果索引越界,它将抛出一个 std::out_of_range 异常。

0