1.潜规则

逻辑运算符的原生语义
—-操作数只有两种值(true和false)
—-逻辑表达式不用完全计算就能确定最终值(短路规则)
—-最终结果只能是true和false

  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. int func(int i)
  5. {
  6. cout << "int func(int i)" << i << endl;
  7. return i;
  8. }
  9. int main()
  10. {
  11. int a = 0;
  12. int b = 1;
  13. if(func(0) && func(1))
  14. {
  15. cout << "True" << endl;
  16. }
  17. else
  18. {
  19. cout << "False" << endl;
  20. }
  21. cout << endl;
  22. if(func(0) || func(1))
  23. {
  24. cout << "True" << endl;
  25. }
  26. else
  27. {
  28. cout << "False" << endl;
  29. }
  30. return 0;
  31. }
  32. int func(int i)0
  33. False
  34. int func(int i)0
  35. int func(int i)1
  36. True

问题:

2.重载逻辑操作符

逻辑操作符可以重载吗?逻辑操作符重载有什么意义?

  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. class Test
  5. {
  6. int mValue;
  7. public:
  8. Test(int v)
  9. {
  10. mValue = v;
  11. }
  12. int value() const//是c++里面的bai关键字const的用法之一,只能用于成员函数,标识在这个函数中不能改变成员变量的值
  13. {
  14. return mValue;
  15. }
  16. };
  17. bool operator && (const Test& l, const Test& r)
  18. {
  19. return l.value() && r.value();
  20. }
  21. bool operator || (const Test& l, const Test& r)
  22. {
  23. return l.value() || r.value();
  24. }
  25. Test func(Test i)
  26. {
  27. cout << "Test func(Test i) : i.value() = " << i.value() << endl;
  28. return i;
  29. }
  30. int main()
  31. {
  32. Test t0(0);
  33. Test t1(1);
  34. if( func(t0) && func(t1) )
  35. {
  36. cout << "Result is true!" << endl;
  37. }
  38. else
  39. {
  40. cout << "Result is false!" << endl;
  41. }
  42. cout << endl;
  43. if( func(1) || func(0) )
  44. {
  45. cout << "Result is true!" << endl;
  46. }
  47. else
  48. {
  49. cout << "Result is false!" << endl;
  50. }
  51. return 0;
  52. }
  53. delphi@delphi-vm:~$ ./a.out
  54. False
  55. True
  56. delphi@delphi-vm:~$ g++ test.cpp
  57. delphi@delphi-vm:~$ ./a.out
  58. Test func(Test i) : i.value() = 1
  59. Test func(Test i) : i.value() = 0
  60. Result is false!
  61. Test func(Test i) : i.value() = 0
  62. Test func(Test i) : i.value() = 1
  63. Result is true!

3.问题的本质分析

—-c++通过函数调用扩展操作符的功能
——进入函数体之前必须完成所有参数的计算
—-函数参数的计算次序是不确定的
—-短路法则完全失效

函数调用的形式:
if( operator &&(func(t0) , func(t1)) )
{
cout << “Result is true!” << endl;
}
else
{
cout << “Result is false!” << endl;
}

逻辑操作符重载后无法实现原生语义

4.一些有用的建议

实际工程开发中避免重载逻辑操作符
通过重载比较操作符代笔逻辑操作符重载
直接使用成员函数代替逻辑操作符重载
使用全局函数对逻辑操作符进行重载

小结:
c++从语法上支持逻辑操作符重载
重载后的逻辑操作符不满足短路法则
工程开发中不要重载逻辑操作符
通过重载比较操作符代笔逻辑操作符重载
直接使用成员函数代替逻辑操作符重载
使用全局函数对逻辑操作符进行重载