第38课 逻辑操作符的陷阱

本文内容来自于对狄泰学院 唐佐林老师 C++深度解析 课程的学习总结

潜规则

关于逻辑运算符的原生语义

操作数只有两种值(true false)
逻辑表达式 不用完全计算就能确定最终值
最终结果只能是 true 或者 false

编程实验
下面来写一段代码来测试逻辑表达式

#include <iostream>

using namespace std;

int func(int i)
{
    cout << "i = " << i << endl;
    return i;
}

int main()
{
    if(func(0) && (func(1)))
        cout << "&& true" << endl;
    else
    {
        cout << "&& false" << endl;
    }

    if(func(0) || func(1))
        cout << "|| true" << endl;
    else
    {
        cout << "|| false" << endl;
    }
    
    return 0;
}

运行结果
在这里插入图片描述

实验结果:逻辑表达式 不用完全计算就能确定最终值,&&运算时func(0)已经能确认结果为false了,所以&&右边的func(1)并没有执行

重载逻辑操作符

实验代码

#include <iostream>
#include <string>

using namespace std;

class Test
{
    int mValue;
public:
    Test(int v)
    {
        mValue = v;
    }
    int value() const
    {
        return mValue;
    }
};

bool operator && (const Test& l, const Test& r)
{
    return l.value() && r.value();
}

bool operator || (const Test& l, const Test& r)
{
    return l.value() || r.value();
}

Test func(Test i)
{
    cout << "Test func(Test i) : i.value() = " << i.value() << endl;
    
    return i;
}

int main()
{
    Test t0(0);
    Test t1(1);
    
    if( func(t0) && func(t1) )
    {
        cout << "Result is true!" << endl;
    }
    else
    {
        cout << "Result is false!" << endl;
    }
    
    cout << endl;
    
    if( func(1) || func(0) )
    {
        cout << "Result is true!" << endl;
    }
    else
    {
        cout << "Result is false!" << endl;
    }
    
    return 0;
}

运行结果
在这里插入图片描述

实验结果:逻辑表达式需要完全计算才能确定最终值

问题的本质分析

1.C++通过函数调用扩展操作符的功能
2.进入函数体前必须完成所有参数的计算
3.函数参数的计算次序是不定的
4.短路法则完全失效

逻辑操作符重载后无法完全实现原生的语义

一些有用的建议

实际开发工程中避免重载逻辑操作符
通过重载比较操作符代替逻辑操作符重载
直接使用成员函数代替逻辑操作符重载
使用全局函数对逻辑操作符进行重载




小结

C++ 从 语法上支持 逻辑操作符重载
重载后的逻辑操作符 不满足短路法则
工程开发中 不要重载逻辑操作符
通过重载 比较操作符 替换逻辑操作符重载
通过 专用成员函数 替换逻辑操作符重载

发布了42 篇原创文章 · 获赞 0 · 访问量 965

猜你喜欢

转载自blog.csdn.net/lzg2011/article/details/104466660