-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmy_string.cpp
More file actions
68 lines (61 loc) · 1.49 KB
/
Copy pathmy_string.cpp
File metadata and controls
68 lines (61 loc) · 1.49 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
#include <iostream>
#include <cstring>
using std::strlen, std::strcpy, std::cin, std::cout, std::endl;
// no two MyString objects point to same "str"
// String.str could not be NULL
class MyString
{
private:
char *str;
public:
MyString(const char *s = "") : str(new char[strlen(s)+1]) { strcpy(str, s); }
MyString(const MyString &s) {MyString(s.str);}
~MyString(){delete[] str;}
const char *to_str() { return str; }
MyString &operator=(const char *s)
{
cout << "call &operator=(const char *s)" << endl;
if (s != str)
{
delete[] str;
str = new char[strlen(s) + 1];
strcpy(str, s);
}
return *this;
}
MyString &operator=(const MyString &z1)
{
cout << "call &operator=(const MyString &)" << endl;
return operator=(z1.str);
}
};
void test_my_string()
{
cout << endl
<< "test_my_string" << endl;
MyString z1("world"), z2, z3;
z2 = "hello ";
z3 = z1;
cout << z2.to_str() << z3.to_str() << endl;
}
void test_cstring()
{
cout << endl
<< "test_ctring" << endl;
char *p = new char[3];
p[0] = '0';
cout << "new char[3]" << endl;
p[2] = '\0';
cout << "p[2]=end strlen: " << strlen(p) << endl;
p[1] = '\0';
cout << "p[1]=end strlen: " << strlen(p) << endl;
p[0] = '\0';
cout << "p[0]=end strlen: " << strlen(p) << endl;
delete[] p;
}
int main()
{
test_cstring();
test_my_string();
return 0;
}