溫馨提示×

c++ operator[] 如何重載

c++
小樊
104
2024-12-02 15:45:50
欄目: 編程語言

在 C++ 中,可以通過重載 operator[] 來實現數組或容器的訪問操作符。以下是一個示例,演示了如何重載 operator[] 以實現一個簡單的類 MyArray 的訪問操作符:

#include <iostream>

class MyArray {
public:
    // 構造函數
    MyArray(int size) : size_(size), data_(new int[size]) {}

    // 析構函數
    ~MyArray() { delete[] data_; }

    // 重載 operator[] 以實現訪問操作符
    int& operator[](int index) {
        if (index < 0 || index >= size_) {
            throw std::out_of_range("Index out of range");
        }
        return data_[index];
    }

    // 重載 operator[] 以實現常量訪問操作符
    const int& operator[](int index) const {
        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);

    // 使用重載的 operator[] 設置和獲取元素值
    arr[0] = 10;
    arr[1] = 20;
    arr[2] = 30;
    arr[3] = 40;
    arr[4] = 50;

    // 輸出元素值
    std::cout << "arr[0] = " << arr[0] << std::endl;
    std::cout << "arr[1] = " << arr[1] << std::endl;
    std::cout << "arr[2] = " << arr[2] << std::endl;
    std::cout << "arr[3] = " << arr[3] << std::endl;
    std::cout << "arr[4] = " << arr[4] << std::endl;

    return 0;
}

在這個示例中,我們定義了一個名為 MyArray 的類,它包含一個整數數組 data_ 和一個表示數組大小的整數 size_。我們重載了 operator[] 以實現訪問操作符,使得可以通過 arr[index] 語法來訪問數組元素。同時,我們還重載了常量版本的 operator[],以便在常量對象上使用。

注意,為了確保數組訪問的安全性,我們在重載的 operator[] 中添加了邊界檢查,并在索引超出范圍時拋出 std::out_of_range 異常。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女