C++逻辑运算符重载的陷阱

C++逻辑运算符重载的使用

在各种编程语言中,都提供了逻辑运算符,包括与(&&)、或()、异或()等等。
C++提供了强大的运算符重载的功能,这里记录一下重载逻辑运算符的陷阱。

逻辑运算符的短路原则

C++逻辑运算符重载

#include <iostream>

using namespace std;

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

    bool operator||(const Test& r)
    {
        return this->getValue() || r.getValue();
    }

    bool operator&&(const Test& r)
    {
        return this->getValue() && r.getValue();
    }

};

Test fun(Test t)
{
    cout << "int fun(Test t), t = " << t.getValue() << endl;
    return t;
}

int main()
{
    Test a(0);
    Test b(1);

    cout << (fun(a) || fun(b)) << endl;
    cout << endl;
    cout << (fun(a) && fun(b)) << endl;

    return 0;
}

短路原则失效

上面程序的运行结果:
int fun(Test t), t = 1
int fun(Test t), t = 0
1

int fun(Test t), t = 1
int fun(Test t), t = 0
0

使用逻辑运算符重载的建议

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


   转载规则


《C++逻辑运算符重载的陷阱》 rookiegan 采用 知识共享署名 4.0 国际许可协议 进行许可。
 上一篇
C语言变量的属性 C语言变量的属性
C语言中的变量可以有自己的属性,在定义变量是可以加上属性关键字,属性关键字指明变量有着特殊的含义。C语言中有着auto、register、static、const、extern等属性关键字。 autoauto是C语言中局部变量的默认属性,a
2017-09-08 rookiegan
本篇 
C++逻辑运算符重载的陷阱 C++逻辑运算符重载的陷阱
C++逻辑运算符重载的使用在各种编程语言中,都提供了逻辑运算符,包括与(&&)、或()、异或()等等。C++提供了强大的运算符重载的功能,这里记录一下重载逻辑运算符的陷阱。 逻辑运算符的短路原则C++逻辑运算符重载#incl
2017-08-04
  目录