Function Overloading & Default Arguments(Chapter 7 of Thinking in C++)
时间:2010-11-12 来源:Ray Z
Mem.cpp 1 #include "Mem.h"
2 #include <cstring>
3 using namespace std;
4
5 Mem::Mem()
6 {
7 mem = 0;
8 size = 0;
9 }
10
11 Mem::Mem(int sz)
12 {
13 mem = 0;
14 size = 0;
15 ensureMinSize(sz);
16 }
17
18 Mem::~Mem()
19 {
20 delete []mem;
21 }
22
23 int Mem::msize()
24 {
25 return size;
26 }
27
28 void Mem::ensureMinSize(int minSize)
29 {
30 if(size < minSize)
31 {
32 byte* newmem = new byte[minSize];
33 memset(newmem+size, 0, minSize - size);
34 memcpy(newmem, mem, size);
35
36 delete []mem;
37 mem = newmem;
38 size = minSize;
39 }
40 }
41
42 byte* Mem::pointer()
43 {
44 return mem;
45 }
46
47 byte* Mem::pointer(int memSize)
48 {
49 ensureMinSize(memSize);
50 return mem;
51 }
MemTest.cpp 1 #include "Mem.h"
2 #include <cstring>
3 #include <iostream>
4 using namespace std;
5
6 class MyString
7 {
8 Mem* buf;
9 public:
10 MyString();
11 MyString(char* str);
12 ~MyString();
13 void concat(char* str);
14 void print(ostream& os);
15 };
16
17 MyString::MyString()
18 {
19 buf = 0;
20 }
21
22 MyString::MyString(char* str)
23 {
24 buf = new Mem(strlen(str) + 1);
25 strcpy((char*)buf->pointer(), str);
26 }
27
28 void MyString::concat(char* str)
29 {
30 if(!buf)
31 {
32 buf = new Mem;
33 }
34
35 strcat((char*)buf->pointer(buf->msize() + strlen(str) + 1), str);
36 }
37
38 void MyString::print(ostream& os)
39 {
40 if(!buf)
41 {
42 return;
43 }
44 os << buf->pointer() << endl;
45 }
46
47 MyString::~MyString()
48 {
49 delete []buf;
50 }
51
52 int main()
53 {
54 MyString s("My test string");
55 s.print(cout);
56 s.concat(" some additional stuff");
57 s.print(cout);
58 MyString s2;
59 s2.concat("Using default constructor");
60 s2.print(cout);
61
62 cin.get();
63 }
相关阅读 更多 +