C++之逻辑操作符的陷阱

逻辑操作符的陷阱

逻辑运算的原生语义

1、操作数只有两种值(true和false)
2、逻辑表达式不用完全计算就能确定最终值;(短路规则)
3、最终结果只能是true或者是false。

编程实验

#include <stdio.h>
#include <iostream>
#include <cstring>


using namespace std;
int main()
{
	int a = 0;
	int b = 1;
	if(a && b)
	{
		cout << "is true" << endl;
	}
	else
	{
		cout << "is false" << endl;
	}
	
	cout << endl;
	
	if(a || b)
	{
		cout << "is true" << endl;
	}
	else
	{
		cout << "is false" << endl;
	}	
	
    return 0;
}

实例分析2:

#include <stdio.h>
#include <iostream>
#include <cstring>


using namespace std;


class Test
{	
	int i;
public:
	Test()
	{
		
	}
	
	Test(int i)
	{
		//cout << "Test(int i)" << endl;
		
		this->i = i;
	}
	
	int getI() const
	{
		return i;
	}

	~Test()
	{
		//cout << "~Test()" << endl;
	}
	

};

bool operator && (const Test& l, const Test& r)
{
	return l.getI() && r.getI();
}

bool operator || (const Test& l, const Test& r)
{
	return l.getI() || r.getI();
}

Test func(Test i)
{
	cout << "int func(int i) : i.getI() = " << i.getI() << endl;
	
	return i;
}

int main()
{
	Test t0(0);
	Test t1(1);
	
	if(func(t0) && func(t1))
	{
		cout << "is true" << endl;
	}
	else
	{
		cout << "is false" << endl;
	}

	if(func(t0) || func(t1))
	{
		cout << "is true" << endl;
	}
	else
	{
		cout << "is false" << endl;
	}		
	
    return 0;
}

在这里插入图片描述

问题本质的分析

1、C++通过函数调用扩展操作符的功能;
2、进入函数体前必须完成所有参数的计算;
3、函数参数的计算次序是不定的;
4、短路法则完全就失效了。

实例分析3;

#include <stdio.h>
#include <iostream>
#include <cstring>


using namespace std;


class Test
{	
	int i;
public:
	Test()
	{
		
	}
	
	Test(int i)
	{
		//cout << "Test(int i)" << endl;
		
		this->i = i;
	}
	
	int getI() const
	{
		return i;
	}

	~Test()
	{
		//cout << "~Test()" << endl;
	}
	

};

bool operator && (const Test& l, const Test& r)
{
	return l.getI() && r.getI();
}

bool operator || (const Test& l, const Test& r)
{
	return l.getI() || r.getI();
}

Test func(Test i)
{
	cout << "int func(int i) : i.getI() = " << i.getI() << endl;
	
	return i;
}

int main()
{
	Test t0(0);
	Test t1(1);
	
	if(operator && (func(t0)func(t1)))
	{
		cout << "is true" << endl;
	}
	else
	{
		cout << "is false" << endl;
	}

	if(operator ||(func(t0)func(t1)))
	{
		cout << "is true" << endl;
	}
	else
	{
		cout << "is false" << endl;
	}		
	
    return 0;
}

在这里插入图片描述

一些有用的建议

1、实际工程开发中避免重载逻辑操作符(这回改变逻辑操作符的原生语义);
2、通过重载比较操作符代替逻辑操作符重载;
3、直接使用成员函数代替逻辑操作符的重载;
4、使用全局函数对逻辑操作符进行重载。

小结

1、C++从语法上支持逻辑操作符的重载;
2、重载后的逻辑操作符不满足短路法则;
3、工程开发中不要重载逻辑操作符;
4、通过重载比较操作符替换逻辑操作符重载;
5、通过专用成员函数替换逻辑操作符。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值