#include<iostream>
#include<cstring>
using namespace std;
class String
{
private:
char* head;
public:
String();
String(char* s);
String(String &s);
~String();
String& operator=(char* s);
String& operator=(String &s);
String operator+=(String &s);
String& operator+(String &s);
bool operator==(String &s);
bool operator<(String &s);
char& operator[](int index);
int Length();
friend istream& operator>>(istream &is,String &s);
};
String::String()
{
head=new char[1];
*head=0;
}
String::String(char* s)
{
int i=strlen(s);
head=new char[i+1];
strcpy(head,s);
}
String:: String(String &s)
{
int i=strlen(s.head);
head=new char[i+1];
strcpy(head,s.head);
}
String:: ~String() {delete[]head;}
String& String::operator=(char* s)
{
int len=strlen(s);
char* newhead=new char[len+1];
strcpy(newhead,s);
delete[]head;
head=newhead;
return *this;
}
String& String::operator=(String &s)
{
int len=strlen(s.head);
char* newhead=new char[len+1];
strcpy(newhead,s.head);
delete[]head;
head=newhead;
return *this;
}
String String::operator+=(String &s)
{
int len=strlen(head)+strlen(s.head);
char* newhead=new char[len+1];
strcpy(newhead,head);
strcat(newhead,s.head);
delete[]head;
head=newhead;
return *this;
}
String& String::operator+(String &s)
{
int len=strlen(head)+strlen(s.head);
char* newhead=new char[len+1];
strcpy(newhead,head);
strcat(newhead,s.head);
String temp;
delete[]temp.head;
temp.head=newhead;
return temp;
}
bool String::operator==(String &s)
{
if(strcmp(head,s.head)==0) return true;
else return false;
}
bool String::operator<(String &s)
{
if(strcmp(head,s.head)<0) return true;
else return false;
}
char& String::operator[](int index)
{
return head[index];
}
int String::Length()
{
return strlen(head);
}
ostream& operator<<(ostream &os,String &s)
{
int i;
for(i=0;s[i];i++) os<<s[i];
return os;
}
istream& operator>>(istream &is,String &s)
{
char c[100];
delete[]s.head;
s.head=new char[100];
cin>>c;
strcpy(s.head,c);
return is;
}
int main()
{
String s1("Help!"),s2("Good!"),s3(s2),s4,s5;
cout<<"s1="<<s1<<endl;
s3="Hello!";
cout<<"s3="<<s3<<endl;
s3+=s2;
cout<<"s3="<<s3<<endl;
cin>>s4;
cout<<"s4="<<s4<<endl;
s5=s3+s4;
cout<<"s5="<<s5<<endl;
s5[0]='g';
cout<<"s5="<<s5<<endl;
cout<<"strlen(s5)="<<s5.Length()<<endl;
cout<<boolalpha<<(s3==s1)<<endl;
cout<<boolalpha<<(s3<s1)<<endl;
return 0;
}
运行结果
s1=Help!
s3=Hello!
s3=Hello!Good!
dgsciuwgi
s4=dgsciuwgi