/* 代码功能:重载双目运算符 作者:令狐荣豪 时间:2019/6/29 */ #include<iostream> using namespace std; class String { public: String() //定义默认构造函数 { p = NULL; } String(char *str);//声明构造函数 friend bool operator>(String &string1, String &string2);//声明重载函数为友元函数 /*====================扩展==============================*/ friend bool operator <(String &string1, String &string2); friend bool operator==(String &string1, String &string2); /*======================================================*/ void display(); void compare(); private: char *p; }; String::String(char *str)//定义构造函数 { p = str;//使p指向实参字符串 } void String::display()//输出p指向的字符串 { cout << p; } /*定义重载运算符函数*/ /*----------------------------------------------*/ bool operator >(String &string1, String &string2) { if (strcmp(string1.p, string2.p) > 0) return true; else return false; } /*----------------------------------------------*/ bool operator <(String &string1, String &string2) { if (strcmp(string1.p, string2.p) < 0) return true; else return false; } /*----------------------------------------------*/ bool operator ==(String &string1, String &string2) { if (strcmp(string1.p, string2.p) == 0) return true; else return false; } /*-----------------------------------------------*/ void compare(String &string1, String &string2) { if (operator>(string1, string2) == 1) { string1.display(); cout << ">"; string2.display(); cout << endl; } if (operator<(string1, string2) == 1) { string1.display(); cout << "<"; string2.display(); cout << endl; } if (operator==(string1, string2) == 1) { string1.display(); cout << "=="; string2.display(); cout << endl; } } int main() { String string1("Hello"), string2("Book"),string3("Computer"),string4("Hello");//定义对象 compare(string1, string2); compare(string2, string3); compare(string1, string4); return 0; }