逻辑与、逻辑或 重载

 问题:为什么不要重载 &&  ||  操作符

因为 &&  || 内置实现了短路规则  例如if(a1 && (a1 +a2)) 通常先执行a1,如果a1为真 则不再执行(a1 + a2)

逻辑与 逻辑或  可以重载 但是无法实现 短路规则


#include <cstdlib>
#include <iostream>

using namespace std;

class Test
{
	int i;
public:
	Test(int i)
	{
		this->i = i;
	}

	Test operator+ (const Test& obj)
	{
		Test ret(0);

		cout<<"执行+号重载函数"<<endl;
		ret.i = i + obj.i;
		return ret;
	}

	bool operator&& (const Test& obj)
	{
		cout<<"执行&&重载函数"<<endl;
		return i && obj.i;
	}
};

// && 从左向右
void main()
{
	int a1 = 0;
	int a2 = 1;

	cout<<"注意:&&操作符的结合顺序是从左向右"<<endl;

	if( a1 && (a1 + a2) )
	{
		cout<<"有一个是假,则不在执行下一个表达式的计算"<<endl;
	}

	Test t1 = 0;
	Test t2 = 1;

	if ( t1 && (t1 + t2) ) 
	{


			t1.operator&&(   t1 + t2  );
			t1.operator&&(   t1.operator+(t2) );



			//t1  && t1.operator+(t2)  

			// t1.operator(  t1.operator(t2)  )   
			cout<<"两个函数都被执行了,而且是先执行了+"<<endl;
	}

	system("pause");
	return ;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值