逻辑操作符重载

逻辑操作符的语义:

  1.操作数只有两种值。

  2.逻辑表达式不用完全计算就能得出最终值。

  3.最终值只能是ture或则是false

 

逻辑操作符的陷阱:函数的参数计算顺序无法满足逻辑&&和||的语义(短路规则)。

#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( operator && (func(t0),func(t1)) )  // 重载函数的函数调用形式
    if( func(t0) && func(t1) )               // 运行结果func()函数被调用两次,
    {                                        // 原因是重载是通过函数进行的,而函数的参数计算次序不确定(从右到左),所以不能符合&&语义。
        cout << "Result is true!" << endl;
    }
    else
    {
        cout << "Result is false!" << endl;
    }
 
    return 0;
}

 

posted @ 2019-05-09 16:17  张不源  Views(140)  Comments(0Edit  收藏  举报