38-逻辑操作符的陷阱
潜规则
逻辑运算符的原生语义:
- 操作符只有两种值(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(int argc, const char* argv[]) {
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;
}
重载逻辑操作符
逻辑操作符可以重载吗?重载逻辑操作符有什么意义?
【范例代码】重载逻辑操作符
#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(Test i) : i.value() = " << i.value() << endl;
return i;
}
int main(int argc, const char* argv[]) {
Test t0(0);
Test t1(1);
if (func(t0) && func(t1)) {
cout << "Result is true!" << endl;
} else {
cout << "Result is false!" << endl;
}
cout << endl;
if (func(1) || func(0)) {
cout << "Result is true!" << endl;
} else {
cout << "Result is false!" << endl;
}
return 0;
}
问题的本质分析:
- C++通过函数调用扩展操作符的功能
- 进入函数体前必须完成所有参数的计算
- 函数参数的计算次序是不定的
- 短路法则完全失效
【注意】逻辑操作符重载后无法完全实现原生的语义。
一些有用的建议:
- 实际工程开发中避免重载逻辑操作符
- 通过重载比较操作符代替逻辑操作符重载
- 直接使用成员函数代替逻辑操作符重载
- 使用全局函数对逻辑操作符重载