#include<iostream>
#include<cstring>
using namespace std;
class String {
public:
String(const char* c = NULL);//构造函数
String(const String& s) : Cstr(new char[strlen(s.Cstr) + 1]) {//拷贝构造函数
strcpy(Cstr, s.Cstr);
}
~String() {//析构函数
if (Cstr) delete[]Cstr;
}
int Length();//字符串长度
char& operator [](int n);//下标运算符重载
String operator +(const String& s);
String& operator =(const String& s);//重载赋值运算符=//重载加法运算符
String& operator +=(const String& s);//重载运算符+=
bool operator < (const String& s);//重载运算符<
bool operator > (const String& s);//重载运算符>
bool operator == (const String& s);//重载运算符==
friend ostream& operator <<(ostream& output, const String& s);//友元函数重载插入运算符
//friend istream& operator >>(istream& intput, const String& s);//友元函数重载提取运算符
void Screen_output();//屏幕输出
private:
char* Cstr;
};
String::String(const char* c) {//构造函数 const char*c=NULL错误
if (c == NULL) {
Cstr = new char[1];
*Cstr = '\0';//字符0
}
else {
Cstr = new char[strlen(c) + 1];
strcpy(Cstr, c);
}
}
int String::Length() {
int n = strlen(Cstr);
return n;
}
char& String::operator [](int n) {
return Cstr[n];
}
String& String::operator=(const String& s) {
if (Cstr == s.Cstr)
return *this;
else if (NULL == this) {
delete Cstr;
Cstr = new char[strlen(s.Cstr) + 1];
strcpy(Cstr, s.Cstr);
}
else {
strcpy(Cstr, s.Cstr);
}
return *this;
}
String String:: operator +(const String& s) {
char* c = new char[strlen(Cstr) + strlen(s.Cstr) + 1];
c = strcat(Cstr, s.Cstr);
return String(c);
}
String& String:: operator +=(const String& s) {
strcat(Cstr, s.Cstr);
return *this;
}
bool String::operator <(const String& s) {
return strcmp(Cstr, s.Cstr) < 0;
}
bool String::operator >(const String& s) {
return strcmp(Cstr, s.Cstr) > 0;
}
bool String::operator ==(const String& s) {
return strcmp(Cstr, s.Cstr) == 0;
}
ostream& operator << (ostream& output, const String& s) {
output << s.Cstr;
return output;
}
//istream& operator >> (istream& intput, const String& s) {
//intput >> s.Cstr;
//if (intput)
//return intput;
//}
void String::Screen_output() {
String s1("Hello"), s2("word"), s3, s4;
cout << "现有两个字符串:" << "s1=" << s1 << " s2=" << s2 <<endl;
cout << "s1长度为:" << s1.Length() << endl;
s3 = s1 + s2;
cout << "s1+s2=" << s3<< endl;
s1 += s2;
cout << "s1+=s2后,s1=" << s1 << endl;
s4 = s2;
cout << "给s4赋值以后,s4=" << s4 << endl;
s1[0] = 'h';
cout << "改变s1首字符后,s1=" << s1 << endl;
cout << "判断s2是否和s4相等," << boolalpha <<(s2==s4)<< endl;
cout << "判断s3>s1对错," << boolalpha << (s3 > s1) << endl;
cout << "判断s3<s1对错," << boolalpha << (s3 < s1) << endl;
}
int main()
{
String string;
string.Screen_output();
return 0;
}