逗号操作符的分析
逗号操作符
逗号操作符(,)可以构成逗号表达式
1、逗号表达式用于将多个子表达式链接为一个表达式;
2、逗号表达式的值为最后一个子表达的值;
3、逗号表达式中的前N-1个子表达式可以没有返回值;
4、逗号表达式按照从左向右的顺序计算每个子表达式的值。
实例分析:
#include <stdio.h>
#include <iostream>
#include <cstring>
using namespace std;
int func(int i)
{
cout << "int func(int i) = " << i << endl;
return i;
}
int main()
{
int a[3][3] = {
(1, 2, 3),
(4, 5, 6),
(7, 8, 9)
};
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;
}
实例分析2;
#include <stdio.h>
#include <iostream>
#include <cstring>
using namespace std;
int func(int i)
{
cout << "int func(int i) = " << i << endl;
return i;
}
int main()
{
int a[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
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、在C++中重载逗号操作符是合法的;
2、使用全局变量对逗号操作符进行重载;
3、重载函数的参数必须有一个类类型;
4、重载函数的返回值类型必须是引用。
Class& operater , (const Class& a, const Class& b)
{
return const_cast<Class&>(b);
}
实例分析;
#include <stdio.h>
#include <iostream>
#include <cstring>
using namespace std;
class Test
{
int i;
public:
Test(int i)
{
this->i = i;
}
int getI()
{
return i;
}
};
Test& operator ,(const Test& a, const Test& b)
{
return const_cast<Test&>(b);
}
Test func(Test& i)
{
cout << "int func(int i) = " << i.getI() << endl;
return i;
}
int main()
{
Test t0(0);
Test t1(1);
//Test tt = (t0, t1);
Test tt = (func(t0), func(t1));
cout << tt.getI() << endl;
return 0;
}
问题的本质分析
1、C++通过函数调用扩展操作符的功能;
2、进入函数体之前必须完成所有参数的计算;
3、函数参数的计算次序是不定的;
4、重载后无法严格的从左向右计算表达式。
**工程中完全不要重载逗号表达式**
小结
1、逗号表达式从左向右顺序计算每个子表达式的值;
2、逗号表达式的值为最后一个子表达式的值;
3、操作符重载无法完全实现逗号操作符的原生意义;
4、工程开发中不要重载逗号操作符。