c++ (8)-运算符重载(提高)-括号运算符重载

1.括号运算符重载

1.1 现象

如果在调用时候遇到下面的写法,可能会出现两种情况,一种是函数的调用,一种是“()”括号运算符的重载;

1.2 括号运算符重载

 

 【函数调用与运算符重载】

 2.为什么不要重载 && || 操作符?

【原因】

1.&& || C++中非常特殊的操作符,&& || 内置实现了短路规则;
如果使用了c++的重载
“&& 和|| ”无法使实现短路规则;

 1 #include <cstdlib>
 2 #include <iostream>
 3 using namespace std;
 4 class Test
 5 {
 6     int i;
 7 
 8 public:
 9     Test(int i)
10     {
11         this->i = i;
12     }
13     Test operator+(const Test &obj)
14     {
15         Test ret(0);
16         cout << " 执行 +号重载函数 " << endl;
17         ret.i = i + obj.i;
18         return ret;
19     }
20     bool operator&&(const Test &obj)
21     {
22         cout << " 执行 &&重载函数 " << endl;
23         return i && obj.i;
24     }
25 };
26 // && 从左向右
27 void main()
28 {
29     int a1 = 0;
30     int a2 = 1;
31     cout << "注意: &&操作符的结合顺序是从左向右 " << endl;
32     if (a1 && (a1 + a2))
33     {
34         cout << " 有一个是假,则不在执行下一个表达式的计算 " << endl;
35     }
36     Test t1 = 0;
37     Test t2 = 1;
38     If(t1 && (t1 + t2))
39     {
40         //t1&& t1.operator(t2)
41         // t1.operator( t1.operator(t2) )
42         cout << " 两个函数都被执行了,而且是先执行了 +" << endl;
43     }
44     system("pause");
45     return;
46 }

【说明】需要与“运算符的结合性”区别开;

 

 

posted @ 2021-03-04 21:27  OzTaking  阅读(1197)  评论(0)    收藏  举报