-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path05_ArrayClass.cpp
78 lines (74 loc) · 1.61 KB
/
05_ArrayClass.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <iostream>
using namespace std;
class Array
{
int *arr;
int size;
public:
Array(int size = 0) : size(size)
{
arr = new int[size];
cin >> *this;
cout << *this;
}
Array(const Array &obj) : size(obj.size)
{
arr = new int[obj.size];
for (int i = 0; i < size; i++)
arr[i] = obj.arr[i];
cout << *this;
}
Array &operator=(const Array &obj)
{
if (&obj != this)
{
if (size != obj.size)
{
size = obj.size;
delete[] arr;
arr = new int[size];
}
for (int i = 0; i < size; i++)
arr[i] = obj.arr[i];
}
return *this;
}
friend ostream &operator<<(ostream &out, const Array &obj)
{
cout << "The entries in the array = \n";
for (int i = 0; i < obj.size; i++)
out << obj.arr[i] << "\n";
return out;
}
friend istream &operator>>(istream &in, Array &obj)
{
cout << "Enter the entries in the array = \n";
for (int i = 0; i < obj.size; i++)
in >> obj.arr[i];
return in;
}
int operator[](const int &index) const
{
if (index >= 0 && index < size)
return arr[index];
exit(0);
}
int &operator[](const int &index)
{
if (index >= 0 && index < size)
return arr[index];
exit(0);
}
~Array()
{
delete[] arr;
}
};
int main()
{
Array arr(3);
arr[2] = 100;
cout << arr[2] << "\n";
cout << arr;
return 0;
}