逗号操作符(,)可以构成逗号表达式
逗号表达式用于将多个子表达式连接为一个表达式
逗号表达式的值为最后一个子表达式的值
逗号表达式的前N-1个子表达
先来看一个例子
#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),
(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;
}
先进行猜想,我们的while(i<5)会不会变成死循环呢?(i,j)=6根据上面的原则,逗号表达的值为最后一个子表达的值,`所以j==6,看结果
结果:
```bash
sice@sice:~$ ./a.out
func() : i = 0
func() : i = 1
func() : i = 2
func() : i = 3
func() : i = 4
2
5
8
0
0
0
0
0
0
i = 3
j = 6
不是说While没有带大括号时作用范围不是仅仅是跟的语句吗?为什么我们的i++起作用了呢,这是因为我们的func(i)后面跟的是逗号,所以后面的i++也在while的作用域内,这就是逗号操作符的作用,用于将多个子表达式连接为一个表达式,看到我们的二维数组,因为我们这里用的是圆括号,所以逗号表达式的值为最后一个子表达式的值,即表现出2,5,8,未初始化的为0,则得到上述的结果,下面来看重载逗号操作符
在C++中重载逗号操作符是合法的
使用全局函数对逗号操作符进行重载
重载函数的参数必须有一个是类类型
重载函数的返回值类型必须是引用
定义:
Class& operator,(const Class& a,const Class& b)
{
return const_cast<Class&>(b);
}
看接下的这个例子:
#include <iostream>
#include <string>
using namespace std;
class Test
{
private:
int i;
public:
int getI()
{
return i;
}
Test(int a)
{
i = a;
}
};
Test& operator ,(const Test& t1,const Test&t2)
{
return const_cast<Test&>(t2);
}
Test func(Test &i)
{
cout<<"the vaule is "<<i.getI()<<endl;
return i;
}
int main()
{
Test t1(1);
Test t2(2);
Test tt = (func(t1),func(t2));
cout<<"the tt value is "<<tt.getI()<<endl;
return 0;
}
结果:
the vaule is 2
the vaule is 1
the tt value is 2
我们的重载逗号操作符函数并不是我们所说的那样从左向右计算,因为我们的(func(t1),func(t2))可以看作是operator ,(func(t1),func(t2)),而函数的参数的计算次序是不定的,所以造成了这种现象,我们的实际的开发过程不要重载逗号操作符,我们把重载操作函数注释掉,再次执行为以下结果,不要重载就正常啦
the vaule is 1
the vaule is 2
the tt value is 2