潜规则逻辑运算符的原生语义操作符只有两种值 ( true 和 false )逻辑表达式不用完全计算就能确定最终值 ( 短路法则 )最终结果只能是 true 或 false编程实验: 逻辑表达式#include <iostream>#include <string>using namespace std;int func(int i){ cout << “int func(int 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(1) || func(0) ) { cout << “Result is true!” << endl; } else { cout << “Result is false!” << endl; } return 0;}输出:【短路法则】int func(int i) : = 0Result is false!int func(int i) : = 1Result is true!重载逻辑操作符逻辑操作符可以重载吗? 重载逻辑操作符有什么意义?编程实验: 重载逻辑操作符#include <iostream>#include <string>using namespace std;class Test{private: 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(){ 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;}输出:Test func(Test i) : i.value() = 1Test func(Test i) : i.value() = 0Result is false!Test func(Test i) : i.value() = 0Test func(Test i) : i.value() = 1Result is true!问题的本质分析C++ 通过函数调用扩展操作符的功能进入函数体前必须完成所有参数的计算函数参数的计算次序是不定的短路法则完全失效if( func(t0) && func(t1) ) {}if( func(t0) || func(t1) ) {}<==>if( operator && (func(t0), func(t1)) ) {}if( operator || (func(t0), func(t1)) ) {}逻辑操作符重载后无法完全实现原生的语义!!一些有用的建议实际工程开发中避免重载逻辑操作符通过重载比较操作符代替逻辑操作符重载直接使用成员函数代替逻辑操作符重载使用全局函数对逻辑操作符进行重载【推荐】小结C++ 从语法上支持逻辑操作符重载重载后的逻辑操作符不满足短路法则工程开发中不要重载逻辑操作符通过比较操作符替换逻辑操作符重载通过专用成员函数替换逻辑操作符重载以上内容参考狄泰软件学院系列课程,请大家保护原创!