第39课 逗号操作符的分析

逗号操作符:

我们如果重载逗号操作符,必须遵守上面的几点。特别是最后两点。

逗号操作符示例:

 1 #include <iostream>
 2 #include <string>
 3 
 4 using namespace std;
 5 
 6 void func(int i)
 7 {
 8     cout << "func() : i = " << i << endl;
 9 }
10 
11 int main()
12 {   
13     int a[3][3] = {
14         (0, 1, 2),
15         (3, 4, 5),
16         (6, 7, 8)
17     };
18     
19     int i = 0;
20     int j = 0;
21     
22     while( i < 5 )    
23         func(i),
24     
25     i++;
26         
27     for(i=0; i<3; i++)
28     {
29         for(j=0; j<3; j++)
30         {
31             cout << a[i][j] << endl;
32         }
33     }
34     
35     (i, j) = 6;
36     
37     cout << "i = " << i << endl;
38     cout << "j = " << j << endl;
39 
40     return 0;
41 }

第35行等价于 j = 6。

重载逗号操作符:

 重载逗号操作符要用全局函数。

示例程序:

我们将36行改成func调用的形式:

我们期望36行先计算func(t0),再计算func(t1),但是从输出结果可以看出,先计算的是func(t1)。这违背了逗号表达式的原生语义。

问题的本质分析:

我们将重载的逗号操作符注释掉,再次演示:

 1 #include <iostream>
 2 #include <string>
 3 
 4 using namespace std;
 5 
 6 class Test
 7 {
 8     int mValue;
 9 public:
10     Test(int i)
11     {
12         mValue = i;
13     }
14     int value()
15     {
16         return mValue;
17     }
18 };
19 /*
20 Test& operator , (const Test& a, const Test& b)
21 {
22     return const_cast<Test&>(b);
23 }
24 */
25 Test func(Test& i)
26 {
27     cout << "func() : i = " << i.value() << endl;
28     
29     return i;
30 }
31 
32 int main()
33 {   
34     Test t0(0);
35     Test t1(1);
36     Test tt = (func(t0), func(t1));         // Test tt = func(t1);
37     
38     cout << tt.value() << endl; // 1
39     
40     return 0;
41 }

 输出结果如下:

这意味着第36行的逗号表达式严格的从左向右执行了。而且返回了最后一个表达式的值。

工程中不要重载逗号操作符。

小结:

猜你喜欢

转载自www.cnblogs.com/wanmeishenghuo/p/9573832.html