-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMyString.cpp
94 lines (78 loc) · 2.04 KB
/
MyString.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include "MyString.h"
MyString::MyString(const char *str) {
if (str == nullptr) {
_data = nullptr;
return;
}
_data = new char[strlen(str) + 1];
strcpy(_data, str);
_data[strlen(str)] = '\0';
}
MyString::MyString(const MyString &other) {
if (other._data == nullptr) {
_data = nullptr;
return;
}
_data = new char[strlen(other._data) + 1];
strcpy(_data, other._data);
_data[strlen(other._data)] = '\0';
}
MyString &MyString::operator = (const MyString &other) {
if (this == &other) return *this;
if (other._data == nullptr) {
_data = nullptr;
return *this;
}
delete[] _data;
_data = new char[strlen(other._data) + 1];
strcpy(_data, other._data);
_data[strlen(other._data)] = '\0';
return *this;
}
MyString::MyString(MyString &&other) {
if (other._data == nullptr) {
_data = nullptr;
return;
}
_data = new char[strlen(other._data) + 1];
strcpy(_data, other._data);
_data[strlen(other._data)] = '\0';
}
MyString &MyString::operator = (MyString &&other) {
if (this == &other) return *this;
if (other._data == nullptr) {
_data = nullptr;
return *this;
}
delete[] _data;
_data = new char[strlen(other._data) + 1];
strcpy(_data, other._data);
_data[strlen(other._data)] = '\0';
return *this;
}
MyString &MyString::operator + (const MyString &other) {
if (other._data == nullptr) {
return *this;
}
char *temp = new char[strlen(_data) + strlen(other._data) + 1];
strcpy(temp, _data);
strcat(temp, other._data);
delete[] _data;
_data = temp;
return *this;
}
bool MyString::operator == (const MyString &other) {
if (other._data == nullptr) {
return _data == nullptr;
}
return strcmp(_data, other._data) == 0;
}
std::ostream &operator << (std::ostream &out, const MyString &other) {
out << other._data;
return out;
}
MyString::~MyString() {
if (_data == nullptr) return;
delete[] _data;
_data = nullptr;
}