zoukankan      html  css  js  c++  java
  • 逻辑操作符重载

    逻辑操作符的语义:

      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;
    }
  • 相关阅读:
    移动端网页头部meta
    fastclick使用方法
    淘宝店铺
    Yii框架下使用redis做缓存,读写分离
    计算一个页面中的数据库查询次数和用时
    数据库优化设计
    工作中使用频率比较高的常规验证器
    框架结构
    smarty
    PDO
  • 原文地址:https://www.cnblogs.com/zsy12138/p/10839150.html
Copyright © 2011-2022 走看看