在 C++ 中,operator[] 是一个重载的下标运算符,它允许你通过数组或类似的容器类型的对象来访问其元素。要实现一个类的 operator[],你需要遵循以下步骤:
class MyArray {
public:
int& operator[](int index) {
// 实现细节
}
};
int& operator[](int index) {
if (index < 0 || index >= size) {
throw std::out_of_range("Index out of range");
}
return data[index];
}
下面是一个简单的 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 异常。