|
| 1 | +// // Overload subscript operator [] that will be useful when we want to check for an index out of bound. |
| 2 | + |
| 3 | +// // Header files |
| 4 | +#include <iostream> |
| 5 | +#include <conio.h> |
| 6 | +#include <iomanip> |
| 7 | + |
| 8 | +// // use namespace |
| 9 | +using namespace std; |
| 10 | + |
| 11 | +// // define class Array |
| 12 | +class Array |
| 13 | +{ |
| 14 | + |
| 15 | +private: |
| 16 | + // // instance member variables |
| 17 | + int a[5], size = 5; |
| 18 | + |
| 19 | +public: |
| 20 | + // // constructors |
| 21 | + Array() {} |
| 22 | + |
| 23 | + // // instance member function to input matrix |
| 24 | + void inputArray() |
| 25 | + { |
| 26 | + for (int i = 0; i < size; i++) |
| 27 | + { |
| 28 | + cin >> a[i]; |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + // // instance member function to show matrix |
| 33 | + void showArray() |
| 34 | + { |
| 35 | + for (int i = 0; i < size; i++) |
| 36 | + { |
| 37 | + cout << a[i]; |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + // // instance member function to set element |
| 42 | + void setElement(int index, int value) |
| 43 | + { |
| 44 | + if (index >= 0 && index < size) |
| 45 | + a[index] = value; |
| 46 | + else |
| 47 | + cout << "\nInvalid Index..."; |
| 48 | + } |
| 49 | + |
| 50 | + // // instance member function to get element |
| 51 | + int getElement(int index, int value) |
| 52 | + { |
| 53 | + if (index >= 0 && index < size) |
| 54 | + a[index] = value; |
| 55 | + else |
| 56 | + cout << "\nInvalid Index..."; |
| 57 | + } |
| 58 | + |
| 59 | + // // overload subscript ([]) operator for reading element |
| 60 | + int operator[](int index) const |
| 61 | + { |
| 62 | + if (index < 0 || index >= size) |
| 63 | + cout << "\n!!! Invalid Index, Array Index Out of Bound...\n"; |
| 64 | + |
| 65 | + return a[index]; |
| 66 | + } |
| 67 | + |
| 68 | + // // overload subscript ([]) operator for writing element |
| 69 | + int &operator[](int index) |
| 70 | + { |
| 71 | + if (index < 0 || index >= size) |
| 72 | + cout << "\n!!! Invalid Index, Array Index Out of Bound...\n"; |
| 73 | + |
| 74 | + return a[index]; |
| 75 | + } |
| 76 | +}; |
| 77 | + |
| 78 | +// // Main Function Start |
| 79 | +int main() |
| 80 | +{ |
| 81 | + |
| 82 | + Array arr1; // // create object of Array class |
| 83 | + |
| 84 | + // // input elements of array |
| 85 | + cout << "\nEnter 5 Elements of Array => "; |
| 86 | + for (int i = 0; i < 5; i++) |
| 87 | + cin >> arr1[i]; |
| 88 | + |
| 89 | + // // show elements of array |
| 90 | + cout << "\n>>>>>>>>>> Elements of Array Are <<<<<<<<<<<<\n"; |
| 91 | + for (int i = 0; i < 5; i++) |
| 92 | + cout << arr1[i] << " "; |
| 93 | + |
| 94 | + cout << endl; // Add new line |
| 95 | + getch(); |
| 96 | + return 0; |
| 97 | +} |
| 98 | +// // Main Function End |
0 commit comments