逻辑操作符的原生语义:操作数只有两种值(true和false),逻辑表达式不用完全计算就能确定最终值,最终结果只能是true或者false。

逻辑操作符可以重载吗?

#include <iostream>
#include <string>
using namespace std;
int func(int i)
{
    cout << "int func(int i) : i = " << i << endl;
    return i;
}
int main()
{
    if( func(0) && func(1) )
    {
        cout << "Result is true!" << endl;
    }
    else
    {
        cout << "Result is false!" << endl;
    }
    cout << endl;
    
    if( func(0) || func(1) )
    {
        cout << "Result is true!" << endl;
    }
    else
    {
        cout << "Result is false!" << endl;
    }    
    return 0;

}

可以重载逻辑操作符,陷阱:

#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) )                        //operatpr && ( func(t0), func(t1))

    {
        cout << "Result is true!" << endl;
    }
    else
    {
        cout << "Result is false!" << endl;
    }  
    cout << endl;    
    if( func(1) || func(0) )                          //   operatpr || ( func(t0), func(t1))
    {
        cout << "Result is true!" << endl;
    }
    else
    {
        cout << "Result is false!" << endl;
    }    
    return 0;

}

问题的本质分析:

进入函数体之前,两个参数值必须确定。不管参数是什么,func要调用两次。求值顺序是不确定的。c++通过函数调用扩展操作符的功能。进入函数体之前必须完成所有参数的计算。函数参数的计算是不确定的,短路法则完全失效。

逻辑操作符重载后无法实现原生的语义。建议:

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


Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐