逗号操符( , )可以构成逗号表达式

下面看一个逗号表达式的示例:
#include <iostream>
using namespace std;
void func(int i)
{
cout << "func(): i = " << i << endl;
}
int main()
{
int a[3][3] = {
(0, 1, 2),
(3, 4, 5),
(6, 7, 8)
};
int i = 0;
int j = 0;
while(i < 5)
func(i),
i++;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
cout << a[i][j] << endl;
}
}
(i, j) = 6;
cout << "i = " << i << endl;
cout << "j = " << j << endl;
return 0;
}
输出结果如下:
注意三点:
1.使用括号,就不是初始化的方式,就变成了逗号表达式。要想其变成真正的初始化语句,需要把圆括号改成花括号。即
int a[3][3] = {
{0, 1, 2},
{3, 4, 5},
{6, 7, 8}
};
2.这个
while(i < 5)
func(i),
i++;
等价于
while(i < 5)
{
func(i);
i++;
}
3.(i, j) = 6; 按照逗号表达式的规则,就是等价于 j = 6;
下面来尝试一下重载逗号操作符:
#include <iostream>
using namespace std;
class Test
{
int mValue;
public:
Test(int i)
{
mValue = i;
}
int value()
{
return mValue;
}
};
Test& operator , (const Test& a, const Test& b)
{
return const_cast<Test&>(b);
}
Test func(Test& i)
{
cout << "func(): i = " << i.value() << endl;
return i;
}
int main()
{
Test t0(0);
Test t1(1);
Test tt = (func(t0), func(t1));
cout << tt.value() << endl;
return 0;
}
输出结果如下:
其中
Test tt = (func(t0), func(t1));
等价于:
Test tt = (operator , (func(t0), func(t1)));
问题的本质分析
可以看一下不重载会输出什么,把下面这段注释掉。
Test& operator , (const Test& a, const Test& b)
{
return const_cast<Test&>(b);
}
输出如下:
可以看到不重载逗号操作符是按照从左到右执行,重载后反而不正常了,所以逗号操作符没有重载的必要。
注意事项:工程中不要重载逗号操作符!!!