文章作者:爷就是这个范儿
01.#include<iostream.h>
02.#include<string.h>
03.//using namespace std;
04.class Cstring
05.{
06.public:
07. Cstring()
08. {
09. p = new char[1];
10. *p = '';
11. }
12. Cstring(const char *t);
13. Cstring(const Cstring &t);
14. ~Cstring()
15. {
16. delete[]p;
17. }
18. bool operator<(const Cstring &t)const;
19. friend bool operator > (const Cstring &str1,const Cstring &str2);
20. Cstring& operator=(const Cstring &t);
21. Cstring operator+(const Cstring &t)const;
22. bool operator==(const Cstring &t)const;
23. char& operator[](int index);
24.
25. void Show()
26. {
27. cout<<p<<endl;
28. }
29.private:
30. char *p;
31.};
32.
33.Cstring::Cstring(const char *t)
34.{
35. if(t == NULL)
36. t = "";
37. int n = strlen(t);
38. p = new char[n+1];
39. strcpy(p,t);
40.}
41.Cstring::Cstring(const Cstring &t)
42.{
43. p = new char[strlen(t.p)+1];
44. strcpy(p,t.p);
45.}
46.bool Cstring::operator <(const Cstring &t)const
47.{
48. if(strcmp(p, t.p) < 0)
49. return true;
50. else return false;
51.}
52.bool operator > (const Cstring &str1, const Cstring &str2)
53.{
54. if(strcmp(str1.p, str2.p) > 0)
55. return true;
56. else return false;
57.}
58.bool Cstring::operator ==(const Cstring &t)const
59.{
60. return strcmp(p,t.p) == 0;
61.}
62.char& Cstring::operator [](int index)
63.{
64. return p[index];
65.}
66.Cstring Cstring::operator +(const Cstring &t)const
67.{
68. char *pt;
69. pt = new char[strlen(p)+strlen(t.p)+1];
70. strcpy(pt,p);
71. strcat(pt,t.p);
72. Cstring temp(pt);
73. delete[]pt;
74. return temp;
75.}
76.Cstring& Cstring::operator =(const Cstring &t)
77.{
78. if(this == &t)
79. return *this;
80. delete[]p;
81. p = new char[strlen(t.p)+1];
82. strcpy(p,t.p);
83. return *this;
84.}
85.
86.void main()
87.{
88. Cstring s1("Hello");
89. Cstring s2("World");
90. Cstring s3;
91. s1.Show();
92.// if(s1[0]>='A' &&s1[0]<='Z')
93.// s1[0] = s1[0]+32;
94.// s1.Show();
95. cout <<(s1>s2)<<endl;
96. cout <<(s1<s2)<<endl;
97. s3 = s1;
98. s3.Show();
99. s3 = s1+s2;
100. s3.Show();
101.}
在VC6.0下如果将头文件改为:
#include<iostream>
#include<string.h>
using namespace std;
就会出现下列错误
error C2248: 'p' : cannot access private member declared in class 'Cstring'