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使用逻辑运算符重载的建议
在实际工程开发中,尽量避免重载逻辑操作符;
通过重载比较操作符替代逻辑操作符重载;
直接使用成员函数代替逻辑操作符重载;
使用全局函数对逻辑操作符进行重载;