String类运算符重载函数
#include<iostream> #include<cstring> using namespace std; class String { public: String( ){p=NULL;} String(char *str); friend bool operator>(String &s1, String &s2); friend bool operator<(String &s1, String &s2); friend bool operator==(String &s1, String &s2); friend bool operator>=(String &s1, String &s2); friend bool operator<=(String &s1, String &s2); friend bool operator!=(String &s1, String &s2); void display( ); private: char *p; }; String::String(char *str) { p = new char[strlen(str)+1]; strcpy(p, str); } void String::display( ) { cout << p; } bool operator>(String &s1,String &s2) { if(strcmp(s1.p,s2.p)>0) return true; else return false; } bool operator<(String &s1,String &s2) { if(strcmp(s1.p,s2.p)<0) return true; else return false; } bool operator==(String &s1,String &s2) { return !((s1>s2)||(s1<s2)); } bool operator>=(String &s1,String &s2) { return !(s1<s2); } bool operator<=(String &s1,String &s2) { return !(s1>s2); } bool operator!=(String &s1,String &s2) { return ((s1>s2)||(s1<s2)); } void compare(String &s1,String &s2) { if(s1>s2) { s1.display( ); cout<<" > "; s2.display( ); } else if(s1<s2) { s1.display( ); cout<<" < "; s2.display( ); } else if(s1==s2) { s1.display( ); cout<<" = "; s2.display( ); } cout<<endl; } int main( ) { String s1("Hello"),s2("Money"),s3("Girl"),s4("Hello"); compare(s1,s2); compare(s2,s3); compare(s1,s4); return 0; }
时间: 2024-07-30 08:49:54