-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmy_array.cpp
More file actions
80 lines (75 loc) · 1.57 KB
/
Copy pathmy_array.cpp
File metadata and controls
80 lines (75 loc) · 1.57 KB
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
79
80
#include <iostream>
#include <cstring>
using std::cin, std::cout, std::endl;
using std::memcpy;
class MyArray
{
private:
int *ptr;
int size;
public:
MyArray() : ptr(NULL), size(0){};
MyArray(const MyArray &z1)
{
size = z1.length();
ptr = new int[z1.size];
memcpy(ptr, z1.ptr, sizeof(int)*z1.size);
}
~MyArray()
{
if (ptr)
delete[] ptr;
};
int length() const { return size; };
int &operator[](int index) { return ptr[index]; };
MyArray &operator=(MyArray &z1)
{
if (z1.ptr != ptr)
{
if (ptr)
delete[] ptr;
size = z1.length();
ptr = new int[z1.size];
for (int i = 0; i < size; i++)
{
ptr[i] = z1[i];
}
}
return *this;
}
void print_array()
{
if (ptr)
{
for (int i = 0; i < size; i++)
{
cout << ptr[i] << ", ";
}
cout << endl;
}
}
static MyArray range(int num1) { return range(0, num1); }
static MyArray range(int num1, int num2)
{
MyArray ret;
ret.size = num2 - num1;
ret.ptr = new int[ret.size];
for (int i = 0; i < ret.size; i++)
{
ret.ptr[i] = i + num1;
}
return ret;
}
};
int main()
{
MyArray z1(MyArray::range(5)), z2;
z1.print_array();
z1[2] = 233;
z1.print_array();
z2 = z1;
z2[0] = 2333;
z2.print_array();
z1.print_array();
return 0;
}