C++深度解析 逻辑操作符的陷阱 --- 重载逻辑操作符,函数参数调用的求值次序(37)
逻辑运算符的原生语义
操作数只有两种植(true和false)
逻辑表达式不用完全计算就能确定最终值
最终结果只能是true或者false
示例程序:逻辑表达式
#include <iostream>
#include <string>
using namespace std;
int func(int i)
{
cout << "int func(int i) : i = " << i << endl;
return i;
}
int main()
{
if ( func(0) && func(1) )
{
cout << "Result is true!" << endl;
}
else
{
cout << "Result is false!" << endl;
}
cout << endl;
if ( func(0) || func(1) )
{
cout << "Result is true!" << endl;
}
else
{
cout << "Result is false!" << endl;
}
return 0;
}
结果如下:
分析:在逻辑与的代码中,逻辑表达式不用完全计算就能确定最终值,确定了func(0)为假,就不调用func(1)了。短路法则。
重载逻辑操作符
示例程序:
#include <iostream>
#include <string>
using namespace std;
class Test
{
int mValue;
public:
Test(int v)
{
mValue = v;
}
int value() const
{
return mValue;
}
};
bool operator && (const Test& l, const Test& r)
{
return l.value() && r.value();
}
bool operator || (const Test& l, const Test& r)
{
return l.value() || r.value();
}
Test func(Test i)
{
cout << "Test func(int i) : i.value() = " << i.value() << endl;
return i;
}
int main()
{
Test t0(0);
Test t1(1);
//函数参数调用的求值次序,是不确定的
if ( operator && (func(t0),func(t1)) )
{
//等价于 ( func(t0) && func(t1) )
cout << "Result is true!" << endl;
}
else
{
cout << "Result is false!" << endl;
}
cout << endl;
if ( operator || (func(1) ,func(0)) )
{
//等价于 ( func(t0) || func(t1) )
cout << "Result is true!" << endl;
}
else
{
cout << "Result is false!" << endl;
}
return 0;
}
结果如下:
分析:函数参数调用的求值次序是不确定的,上面结果的每一个重载逻辑操作符函数的调用是不确定的。逻辑操作符重载后无法完全实现原生的语义。
一些有用的建议:
实际工程开发中避免重载逻辑操作符
通过重载比较操作符代替逻辑操作符重载
直接使用成员函数代替逻辑操作符重载
使用全局函数对逻辑操作符进行重载
小结
C++从语法上支持逻辑操作符重载
重载后的逻辑操作符不满足短路法则
工程开发中不要重载逻辑操作符
通过重载比较操作符替换逻辑操作符重载
通过专用成员函数替换逻辑操作符重载