脚本宝典收集整理的这篇文章主要介绍了【C++】 38_逻辑操作符的陷阱,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
潜规则
编程实验: 逻辑表达式
#include <iostream>
#include <string>
@H_126_45@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;
}
@H_406_135@输出:【短路法则】
int func(int i) : = 0
Result is false!
int func(int i) : = 1
Result 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() = 1
Test func(Test i) : i.value() = 0
Result is false!
Test func(Test i) : i.value() = 0
Test func(Test i) : i.value() = 1
Result 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++ 从语法上支持逻辑操作符重载
- 重载后的逻辑操作符不满足短路法则
- 工程开发中不要重载逻辑操作符
- 通过比较操作符替换逻辑操作符重载
- 通过专用成员函数替换逻辑操作符重载
以上是脚本宝典为你收集整理的【C++】 38_逻辑操作符的陷阱全部内容,希望文章能够帮你解决【C++】 38_逻辑操作符的陷阱所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。