一、逻辑运算符的原生语义
1.操作符只有两种值(true和false)
2.逻辑表达式不用完全计算就能确定最终值
3.最终结果只能是true或者false
#include<iostream>
using namespace std;
int fun(int i)
{
cout<<"int fun(int i): i="<<i<<endl;
return i;
}
int main()
{
if(fun(0) && fun(1))
{
cout<<"the result is true"<<endl;
}
else
{
cout<<"the result is false"<<endl;
}
cout<<endl;
if(fun(0) || fun(1))
{
cout<<"the result is true"<<endl;
}
else
{
cout<<"the result is false"<<endl;
}
return 0;
}
打印结果:
int fun(int i): i=0
the result is false
int fun(int i): i=0
int fun(int i): i=1
the result is true
二、重载逻辑操作符
#include<iostream>
using namespace std;
class Test
{
private:
int i;
public:
Test(int i)
{
this->i = i;
}
int getI() const
{
return i;
}
};
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 fun(Test i)
{
cout<<"Test fun(Test i): i="<<i.getI()<<endl;
return i;
}
int main()
{
Test t0(0);
Test t1(1);
if(fun(t0) && fun(t1))//operator && (fun(t0), fun(t1)) 则先要算出参数fun(t0)和fun(t1)的值,且这两个的计算顺序不确定
{
cout<<"the result is true"<<endl;
}
else
{
cout<<"the result is false"<<endl;
}
if(fun(t0) || fun(t1))
{
cout<<"the result is true"<<endl;
}
else
{
cout<<"the result is false"<<endl;
}
return 0;
}
打印结果:
Test fun(Test i): i=1
Test fun(Test i): i=0
the result is false
Test fun(Test i): i=1
Test fun(Test i): i=0
the result is true
问题本质分析:
1.c++通过函数调用扩展操作符的功能
2.进入函数体前必须完成所有参数的计算
3.函数参数的计算次序是不确定的
4.短路法则完全失效
所以说逻辑操作符重载后无法完全实现原生语义
建议:
1.实际工程开发中避免重载逻辑操作符
2.通过重载比较操作符代替逻辑操作符重载
3.直接使用成员函数代替逻辑操作符重载
4.直接使用全局函数对操作符进行重载
小结:
1.c++在语法上支持逻辑操作符的重载
2.重载逻辑操作符后不满足短路法则
3.通过重载比较操作符代替逻辑操作符重载
4.通过专用成员函数代替逻辑操作符