c++重载部分运算符以及输入输出运算符

 1 #include<iostream>
 2 using namespace std;
 3 struct tree{
 4     int num;
 5     string s;
 6     bool operator<(const tree &a)const
 7     {
 8         return a.num<num;
 9     }
10     friend bool operator>(const tree a,const tree b)
11     {
12         return a.num<b.num;
13     }
14     bool operator==(const tree &a)const
15     {
16         return a.num==num;
17     }
18     tree operator+(const tree &a)const
19     {
20         tree t;
21         t.num=num+a.num;
22         t.s=s+a.s;
23         return t;
24     }
25     friend istream &operator>>(istream &in,tree &t)
26     {
27         in>>t.num>>t.s;
28 //        return in; 
29     }
30     friend ostream &operator<<(ostream &out, tree &t)
31     {
32         out<<t.num<<" "<<t.s<<endl;
33 //        return out;
34     }
35     /* 重载部分运算符,以及输入输出运算符*/
36 };
37 int main()
38 {
39     tree a,b;
40     cin>>a;
41     cout<<a;
42     cin>>b;
43     cout<<b;
44 //    a.num=5;
45 //    a.s="hello";
46 //    b.num=6;
47 //    b.s="world";
48     if(!(a==b))
49     {
50         cout<<"hh";
51     }
52     else
53     {
54         cout<<"xx";
55     }
56     cout<<endl;
57     a=a+b;
58     cout<<a.num;
59     cout<<endl<<a.s;
60 }

重载输入输出运算符的函数,两个“&”必不可少。

原文地址:https://www.cnblogs.com/dayq/p/11939561.html