跳转至

数组类模板

约 8 个字 54 行代码 预计阅读时间 1 分钟

T a[size]

#include <iostream>
using namespace std;
// 数组类模板
template<typename T, int size>
class Array {
private:
    T arr[size];
public:
    // 设置数组元素
    void set(int index, T value) {
        if (index >= 0 && index < size)
            arr[index] = value;
        else
            cout << "Index out of bounds!" << endl;
    }

    // 获取数组元素
    T get(int index) {
        if (index >= 0 && index < size)
            return arr[index];
        else {
            cout << "Index out of bounds!" << endl;
            return T();
        }
    }

    // 重载 [] 运算符
    T& operator[](int index) {
        if (index >= 0 && index < size)
            return arr[index];
        else {
            cout << "Index out of bounds!" << endl;
            // 返回一个临时变量的引用
            static T temp;
            return temp;
        }
    }
};

int main() {
    // 测试数组类模板
    Array<int, 5> arr;
    arr.set(0, 10);
    arr.set(1, 20);
    cout << arr.get(0)<<endl;
    // 使用 [] 运算符访问元素
    cout << arr[0] << " " << arr[1] << endl;
    // 使用 [] 运算符设置元素
    arr[2] = 30;
    // 再次使用 [] 运算符访问元素
    cout << arr[2] << endl;
    return 0;
}

颜色主题调整

评论区~

有用的话请给我个赞和 star => GitHub stars
快来跟我聊天~