-
Notifications
You must be signed in to change notification settings - Fork 2
/
MyString.h
100 lines (98 loc) · 2.1 KB
/
MyString.h
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
95
96
97
98
99
100
#pragma once
#include <cstring>
#include <iostream>
#include "SimpleAllocate.h"
namespace TinySTL
{
const unsigned MAXSIZE = 10000;
class MyString
{
public:
typedef char value_type;
typedef value_type * pointer;
typedef value_type * iterator;
typedef value_type & reference;
typedef SimpleAllocate<value_type> alloc;
MyString(const char * str = nullptr)
{
if (str == nullptr)
{
data = alloc::allocate(1);
data[0] = '\0';
}
else
{
data = alloc::allocate(strlen(str) + 1);
strcpy(data, str); // 会拷贝
}
}
MyString(MyString &s)
{
data = alloc::allocate(strlen(s.data) + 1);
strcpy(data, s.data);
}
value_type operator[](unsigned index)
{
return data[index];
}
iterator begin()
{
return data;
}
iterator end()
{
return &data[strlen(data)];
}
MyString & operator=(MyString &s)
{
if (this != &s)
{
MyString tmp(s);
auto tmp_s = tmp.data;
tmp.data = data; // 生成一个临时对象,会将原来的地址释放
data = tmp_s;
}
return *this;
}
MyString operator + (MyString &s)
{
MyString tmp;
char * tmp_data = alloc::allocate(strlen(data) + strlen(s.data) + 1);
strcpy(tmp_data, data);
strcpy(tmp_data + strlen(data), s.data);
tmp.data = tmp_data;
return tmp;
}
MyString operator+(const char * str)
{
MyString tmp(str);
return *this + tmp;
}
~MyString()
{
SimpleAllocate<char>::deallocate(data, strlen(data) + 1);
}
friend std::ostream &operator<<(std::ostream & onfs, const MyString & s);
friend std::istream &operator >> (std::istream & infs, MyString &s);
private:
char * data;
};
std::ostream &operator<<(std::ostream & onfs, const MyString & s)
{
onfs << s.data;
return onfs;
}
std::istream &operator >> (std::istream & infs, MyString &s)
{
typedef char value_type;
typedef SimpleAllocate<value_type> alloc;
char * data = alloc::allocate(MAXSIZE);
infs.getline(data, MAXSIZE);
MyString tmp;
tmp.data = s.data; // 释放前面的
s.data = alloc::allocate(strlen(data) + 1);
strcpy(s.data, data);
alloc::deallocate(data, MAXSIZE);
return infs;
}
}