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

本文探讨了C++中逻辑运算符的原生行为及其重载后的特性变化,包括短路法则失效的问题,并提出了几种替代方案。
部署运行你感兴趣的模型镜像

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

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

您可能感兴趣的与本文相关的镜像

ACE-Step

ACE-Step

音乐合成
ACE-Step

ACE-Step是由中国团队阶跃星辰(StepFun)与ACE Studio联手打造的开源音乐生成模型。 它拥有3.5B参数量,支持快速高质量生成、强可控性和易于拓展的特点。 最厉害的是,它可以生成多种语言的歌曲,包括但不限于中文、英文、日文等19种语言

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值