a.逗号表达式用于将多个子表达式连接为一个表达式
b.逗号表达式的值为最后一个子表达式的值
c.逗号表达式中的前N-1个子表达式没有返回值
d.逗号表达式按照从左到右的顺序计算每个表达式的值
eg:
#include <iostream>
#include <string>
using namespace std;
void func(int i)
{
cout << "func(): i = " << i << endl;
}
int main()
{
int a[3][3] = {
(0, 1, 2), //注意这里是(),它只会返回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; //i = 6;
cout << "i = " << i << endl;
cout << "j = " << j << endl;
return 0;
}
eg:
#include <iostream>
#include <string>
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)); //理论上来讲,这里应该是先输出0,在输出1;
cout << tt.value() << endl;
return 0;
}
上诉代码的结果和理论分析的相互矛盾。理论上来说,逗号操作符应该是从左到右的运行。可是重载后就无法实现,这是因为重载就像调用了一个函数一样,在调用函数前编译器需要完成所有参数的计算。而计算的过程的次序是不定的。(同逻辑运算符的重载)
原文:https://www.cnblogs.com/huangdengtao/p/11911286.html