Sunday, February 13, 2022

[c++] Overloading subscripting (C++ only)

 #include <iostream>

using namespace std;


template <class T> class MyArray {

private:

  T* storage;

  int size;

public:

  MyArray(int arg = 10) {

    storage = new T[arg];

    size = arg;

  }


  ~MyArray() {

    delete[] storage;

    storage = 0;

  }


  T& operator[](const int location) throw (const char *);

};


template <class T> T& MyArray<T>::operator[](const int location)

  throw (const char *) {

    if (location < 0 || location >= size) throw "Invalid array access";

    else return storage[location];

}


int main() {

  try {

     MyArray<int> x(13);

     x[0] = 45;

     x[1] = 2435;

     cout << x[0] << endl;

     cout << x[1] << endl;

     x[13] = 84;

  }

  catch (const char* e) {

    cout << e << endl;

  }

}

================================================

45

2435

Invalid array access

No comments:

Post a Comment

n8n index

 【n8n免費本地端部署】Windows版|程式安裝x指令大補帖  【一鍵安裝 n8n】圖文教學,獲得無限額度自動化工具&限時免費升級企業版功能