-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMyString.cpp
More file actions
98 lines (84 loc) · 1.91 KB
/
Copy pathMyString.cpp
File metadata and controls
98 lines (84 loc) · 1.91 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <cstring>
#include <iostream>
#include <cstdlib>
//远端修改,测试冲突
using namespace std;
class MyString
{
public:
MyString(const char* str = nullptr);
MyString(const MyString& r);
MyString(MyString &&other); //移动构造函数
MyString& operator=(const MyString& x);
MyString& operator=(MyString&& x);
private:
char* m_data;
};
MyString::MyString(const char* str)
{
if(str == nullptr)
{
m_data = new char[1];
*m_data = '\0';
cout << "默认构造函数" << endl;
}else
{
int len = strlen(str);
m_data = new char[len + 1];
strcpy(m_data,str);
cout << "有参构造" << endl;
}
}
MyString::MyString(const MyString& r)
{
int len = strlen(r.m_data);
m_data = new char[len + 1];
strcpy(m_data,r.m_data);
cout << "拷贝构造" << endl;
}
MyString::MyString(MyString&& other)
{
//窃取
m_data = other.m_data;
other.m_data = nullptr;
cout << "移动构造" << endl;
}
MyString& MyString::operator=(const MyString& x)
{
//非自赋值
if(this != &x)
{
if(!m_data)
delete[] m_data;
int len = strlen(x.m_data);
m_data = new char[len + 1];
strcpy(m_data,x.m_data);
}
cout << "拷贝赋值" << endl;
return *this;
}
MyString& MyString::operator=(MyString&& x)
{
if(this != &x)
{
delete[] m_data;
m_data = x.m_data;
x.m_data = nullptr;
}
cout << "移动赋值" << endl;
return *this;
}
int main()
{
//system("chcp 69001");
MyString s1; //默认构造
MyString s2("hello"); //参数构造
MyString s3(s2); //拷贝构造
MyString s4(move(s3)); //移动构造
MyString s5;
s5 = s4; //拷贝赋值
MyString s6;
s6 = move(s5); //移动赋值
system("pause");
return 0;
}