-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdemo18.cpp
55 lines (45 loc) · 870 Bytes
/
demo18.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
#include <iostream>
#include <cstring>
using namespace std;
class String
{
public:
// String(const char* chars);
String(char const *chars = "");
String& operator = (String const &);
void print();
private:
char* ptrChars;
};
String::String(char const *chars)
{
chars = chars ? chars : "";
ptrChars = new char[strlen(chars) + 1];
strcpy(ptrChars, chars);
}
void String::print()
{
cout << ptrChars << endl;
}
String& String::operator = (String const &str)
{
if(strlen(this->ptrChars) != strlen(str.ptrChars))
{
char* ptrHold = new char[strlen(str.ptrChars) + 1];
delete[] ptrChars;
ptrChars = ptrHold;
}
strcpy(ptrChars, str.ptrChars);
return *this;
}
int main()
{
String a("hello");
String b("Dog");
cout << "a : " << a << endl;
cout << "b : " << b << endl;
a = b;
cout << "a : " << a << endl;
cout << "b : " << b << endl;
return 0;
}