C++语法小记---重载逻辑操作符

重载逻辑操作符
  • 不建议重载逻辑操作符

  • 原因:无法实现逻辑操作符的短路功能(即:不需要计算完全部表达式就可以得出结果)

  • 逻辑操作符:|| &&

  • 操作符重载本质上是函数调用,而进行函数调用之前一定要计算出所有参数的值,然后才能调用函数,所以无法实现短路功能

 

 1 #include<iostream>
 2 #include<string>
 3 
 4 using namespace std;
 5 
 6 class Test
 7 {
 8     int i;
 9 public:
10     Test(int i = 0)
11     {
12         this->i = i;
13     }
14     
15     int getI()
16     {
17         return i;
18     }
19 };
20 
21 bool operator && (Test& l, Test& r)
22 {
23     return l.getI() && r.getI();
24 }
25 
26 bool operator || (Test& l, Test& r)
27 {
28     return l.getI() || r.getI();
29 }
30 
31 Test& print(Test& t)
32 {
33     cout<<"Test print(Test t) t.i = "<<t.getI()<<endl;
34     return t;
35 }
36 
37 int main()
38 {
39     Test t1(0);
40     Test t2(1);
41     
42     if(print(t1) && print(t2))
43     {
44         cout<<"true"<<endl;
45     }
46     else
47     {
48         cout<<"false"<<endl;
49     }
50     
51     return 0;
52 }
53 //输出结构,没有实现短路功能
54 //Test print(Test t) t.i = 1
55 //Test print(Test t) t.i = 0
56 //false

 

posted @ 2019-08-03 16:32  Yong_无止境  阅读(410)  评论(0编辑  收藏  举报