第三十八课:逻辑操作符的陷阱----------狄泰软件学院

一、逻辑运算符的原生语义

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.通过专用成员函数代替逻辑操作符

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值