问题:为什么不要重载 && || 操作符
因为 && || 内置实现了短路规则 例如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 ;
}