按照常理来讲,&&和||运算符,都是先计算左边的表达式,再计算右边的表达式。如果左边的表达式能够决定整个运算的结果,那么右边的表达式便不会执行。
如果重载了&&和||运算符,将会带来一些不容易发现的错误。
class buer
{
public:
int flag;
public:
buer(int n)
{
flag = n;
}
buer& operator+=(const buer& b)//+=重载
{
this->flag += b.flag;
return *this;
}
buer& operator-=(const buer& b)//-=重载
{
this->flag -= b.flag;
return *(this);
}
bool operator&&(const buer& b)
{
return flag&&b.flag;
}
bool operator||(const buer& b)
{
return flag || b.flag;
}
};
void test()
{
buer b0(0);
buer b1(1);
if (b0 && (b0 += b1))
{//先执行b0+=b1,结果与期望结果相反
cout << "true" << endl;
}
else
{
cout << "false" << endl;
}
if (b0 && (b0 -= b1))
{//先执行b0-=b1,结果与期望结果相反
cout << "true" << endl;
}
else
{
cout << "false" << endl;
}
}