首页 > 编程知识 正文

双目运算符运算法则,双目运算符属于什么运算

时间:2023-05-03 11:20:04 阅读:226494 作者:3711

//重载双目运算符,双目运算符有两个操作数,通常在运算符的左右两侧,在重载双目运算符时,在友元函数中应该有两个参数//思想:要想将运算符用于用户自定义类上,用户必须自己对运算符进行重载。要对“==”,“<”和“>”三个运算符进行重载,需要重新定义3个运算符重载函数。可以将重载函数定义成类成员函数( 1个参数),也可以定义成类的友元函数(两个参数)。//先建立一个string类#include <iostream>using namespace std;class String{public://友元类#include <iostream>#include <cstring>using namespace std;class String{public: String(){p=NULL;} String(char *str); void display(); friend bool operator>(String &string1,String &string2);private: char *p;};String::String(char *str){ p=str;}void String::display(){ cout<<p;}bool operator>(String &string1,String &string2){ if(strcmp(string1.p,string2.p)>0) return true; else return false;}int main(){ String string1("Hello"),string2("Book"); cout<<(string1>string2)<<endl;}String(){p=NULL;}String(char *str);void display();private:char *p;};String::String(char *str){p=str;}void String::display(){cout<<p;//此时输出的是字符串,如果cout<<*p;则输出的是字符踹的首字母}int main(){String string1("Hello"),string2("Book");string1.display();cout<<endl;string2.display();cout<<endl;return 0;} //再扩展到三个#include <iostream>#include <cstring>using namespace std;class String{public:    String(){p=NULL;}    String(char *str);    void display();    friend bool operator>(String &string1,String &string2);    friend bool operator<(String &string1,String &string2); friend bool operator==(String &string1,String &string2);private:    char *p;};String::String(char *str){    p=str;}void String::display(){    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();       if(operator<(string1,string2)==1)           string1.display();cout<<'<';string2.display();     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(string3,string4);    return 0;}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。