-
Notifications
You must be signed in to change notification settings - Fork 1
/
Lab_solution_26.cpp
51 lines (44 loc) · 955 Bytes
/
Lab_solution_26.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <cstdlib>
#include <iostream>
using namespace std;
// A class to represent an integer array
class Array {
private:
int* m_ptr;
int m_size;
public:
Array(int* ptr, int size)
{
m_size = size;
m_ptr = NULL;
if (size != 0) {
m_ptr = new int[size];
for (int i = 0; i < size; i++)
m_ptr[i] = ptr[i];
}
}
// Implementation of [] operator. This function must return a
// reference as array element can be put on left side
int& operator[](int index)
{
if (index < 0) {
cout << "Negative array index is not accepted, exiting";
exit(0);
}
if (index >= m_size) {
cout << "Array index out of bound, exiting";
exit(0);
}
return m_ptr[index];
}
};
int main()
{
int a[] = { 1, 2, 4, 5 };
Array arr(a, 4);
arr[2] = 6;
cout << "arr[2] =" << arr[2] << "\n";
cout << "arr[8] = " << arr[8] << "\n";
cout << "arr[-2] = " << arr[-2] << "\n";
return 0;
}