-
Notifications
You must be signed in to change notification settings - Fork 0
/
array.cpp
61 lines (53 loc) · 986 Bytes
/
array.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
#include "Array.h"
#include <cstdlib>
#include <iostream>
using namespace std;
Array::Array(int size)
{
//constructor
if (size < 0) {
cout << "Error: Size should be positive." << endl;
exit(1);
}
else {
data = new int[size];
len = size;
}
}
Array::~Array()
{
//destructor
delete[] data;
}
int Array::length() const {
//Return the length of the array.
return len;
}
int& Array::operator[](int i) {
static int tmp;
if (i >= 0 && i < len) {
return data[i];
}
else {
cout << "Array bound error!" << endl;
return tmp;
}
}
int Array::operator[](int i) const {
if (i >= 0 && i < len) {
return data[i];
}
else {
cout << "Array bound error!" << endl;
return 0;
}
}
void Array::print() {
int i;
cout << "[";
for (i = 0; i < len-1; i++) {
cout << data[i] << " ";
}
cout << data[i];
cout << "]" << endl;
}