定义一个字符串类,重载运算符,进一步修饰完善
1 #define NULL 0 2 #include <iostream> 3 #include <string.h> 4 /* run this program using the console pauser or add your own getch, system("pause") or input loop */ 5 using namespace std; 6 class String 7 { 8 public: 9 String(){ 10 p=NULL; 11 } 12 String(char *str); 13 friend bool operator>(String &string1,String &string2); 14 friend bool operator<(String &string1,String &string2); 15 friend bool operator==(String &string1,String &string2); 16 void display(); 17 private: 18 char *p; 19 }; 20 21 String::String(char *str) 22 { 23 p=str; 24 } 25 26 void String::display() 27 { 28 cout<<p; 29 } 30 31 bool operator>(String &string1,String &string2) 32 { 33 if(strcmp(string1.p,string2.p)>0) 34 return true; 35 else return false; 36 } 37 38 bool operator<(String &string1,String &string2) 39 { 40 if(strcmp(string1.p,string2.p)<0) 41 return true; 42 else return false; 43 } 44 45 bool operator==(String &string1,String &string2) 46 { 47 if(strcmp(string1.p,string2.p)==0) 48 return true; 49 else return false; 50 } 51 52 void compare(String &string1,String &string2) 53 { 54 if(operator>(string1,string2)==1) 55 { 56 string1.display(); 57 cout <<">"; 58 string2.display(); 59 }else if(operator<(string1,string2)==1) 60 { 61 string1.display(); 62 cout <<"<"; 63 string2.display(); 64 }else if(operator==(string1,string2)==1) 65 { 66 string1.display(); 67 cout <<"="; 68 string2.display(); 69 } 70 cout<<endl; 71 } 72 int main(int argc, char** argv) { 73 String string1("Hello"),string2("Book"),string3("Computer"),string4("Hello"); 74 compare(string1,string2); 75 compare(string2,string3); 76 compare(string1,string4); 77 return 0; 78 }