#include<iostream.h>
#include<string.h>
//using namespace std;
class Cstring
{
public:
Cstring()
{
p = new char[1];
*p = '\0';
}
Cstring(const char *t);
Cstring(const Cstring &t);
~Cstring()
{
delete[]p;
}
bool operator<(const Cstring &t)const;
friend bool operator > (const Cstring &str1,const Cstring &str2);
Cstring& operator=(const Cstring &t);
Cstring operator+(const Cstring &t)const;
bool operator==(const Cstring &t)const;
char& operator[](int index);
void Show()
{
cout<<p<<endl;
}
private:
char *p;
};
Cstring::Cstring(const char *t)
{
if(t == NULL)
t = "";
int n = strlen(t);
p = new char[n+1];
strcpy(p,t);
}
Cstring::Cstring(const Cstring &t)
{
p = new char[strlen(t.p)+1];
strcpy(p,t.p);
}
bool Cstring::operator <(const Cstring &t)const
{
if(strcmp(p, t.p) < 0)
return true;
else return false;
}
bool operator > (const Cstring &str1, const Cstring &str2)
{
if(strcmp(str1.p, str2.p) > 0)
return true;
else return false;
}
bool Cstring::operator ==(const Cstring &t)const
{
return strcmp(p,t.p) == 0;
}
char& Cstring::operator [](int index)
{
return p[index];
}
Cstring Cstring::operator +(const Cstring &t)const
{
char *pt;
pt = new char[strlen(p)+strlen(t.p)+1];
strcpy(pt,p);
strcat(pt,t.p);
Cstring temp(pt);
delete[]pt;
return temp;
}
Cstring& Cstring::operator =(const Cstring &t)
{
if(this == &t)
return *this;
delete[]p;
p = new char[strlen(t.p)+1];
strcpy(p,t.p);
return *this;
}
void main()
{
Cstring s1("Hello");
Cstring s2("World");
Cstring s3;
s1.Show();
// if(s1[0]>='A' &&s1[0]<='Z')
// s1[0] = s1[0]+32;
// s1.Show();
cout <<(s1>s2)<<endl;
cout <<(s1<s2)<<endl;
s3 = s1;
s3.Show();
s3 = s1+s2;
s3.Show();
}
在VC6.0下如果将头文件改为:
#include<iostream>
#include<string.h>
using namespace std;
就会出现下列错误
error C2248: 'p' : cannot access private member declared in class 'Cstring'