Logical AND, logical or reload

 Question: Why do not overload operator && ||

Because a short-circuit && || built rules implemented e.g. if (a1 && (a1 + a2)) is typically performed to a1, a1 is true if it is no longer performed (a1 + a2)

Logic and logic but not overload or short-circuit may rule


#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 ;
}



Published 33 original articles · won praise 2 · Views 8524

Guess you like

Origin blog.csdn.net/QQ960054653/article/details/60463605