Overloading Constructors and Copy Constructors
It is common practice to overload constructors, providing them with different argument types for different situations. The default constructor is one that has no arguments. A copy constructor is one that copies an existing instance of a class. It is common practice to use reference to a const class object as the argument of a copy constructor.
Example 4-10 - The text class
1 File: ex4-10.cpp
2
3 #include <iostream>
4 #include <cstring>
5 using namespace std;
6
7 class text
8 {
9 private:
10 char* s;
11 int length;
12 public:
13 text(void); // default constructor
14 text(const char *);
15 text(const text&); // copy constructor
16 text(int);
17 text(char);
18 ~text() { delete [] s; } // inline destructor
19 void print(void) const;
20 };
21
22 text::text(void) {
23 s = new char[1];
24 s[0] = '\0';
25 length = 0;
26 }
27
28 text::text(const char* str)
29 {
30 s = new char[strlen(str) + 1];
31 length = strlen(str);
32 strcpy(s,str);
33 }
34
35 text::text(const text& str)
36 {
37 length = str.length;
38 s = new char[length + 1];
39 strcpy(s,str.s);
40 }
41 text::text(int len)
42 {
43 length = len;
44 s = new char[length + 1];
45 }
46
47 text::text(char ch)
48 {
49 length = 1;
50 s = new char[2];
51 s[0] = ch;
52 s[1] = '\0';
53 }
54
55 void text::print(void) const
56 {
57 cout << s << endl;
58 }
59
60 int main(void)
61 {
62 text a("Have a nice day");
63 a.print();
64
65 text b(a);
66 b.print();
67
68 text c; // Note: do not use text c();
69 c.print();
70
71 text d(15);
72 d.print();
73
74 text e('x');
75 e.print();
76
77 return 0;
78 }****** Output ******
Have a nice day
Have a nice day
----------------²²²² What's this?
x
沒有留言:
張貼留言