重载逻辑操作符:
问题本质分析:
1,C++通过函数调用扩展操作符的功能
2,进入函数体前必须完成所有的参数的计算
3,函数参数的计算次序是不定的
4,短路法则完全失效
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() { 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; }
建议:
工程开发中不要重载逻辑操作符
通过重载比较操作符替换逻辑操作符重载
通过专用的成员函数替换逻辑操作符重载