1 原生的逻辑操作符
对于原生的逻辑 && 和 || 操作符,我们知道结果只有两种值(true 和 false),并且逻辑操作符有短路法则
实例分析:回顾原生的逻辑操作符
// 26-1.cpp
#include<iostream>
using namespace std;
int func(int i)
{
cout << "int func(int):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;
}
- 表达式 func(0) && func(1) 中 func(0) 为 0,所以表达式为 false,func(1)不会进行计算了。
- 表达式 func(0) || func(1) 中,func(0) 为 false,所以 func(1) 还会计算。
编译运行:
$ g++ 26-1.cpp -o 26-1
$ ./26-1
int func(int):i = 0
Result is false
int func(int):i = 0
int func(int):i = 1
Result is true
结果和我们期待的一样。
2 重载逻辑运算符
如果我们重载逻辑操作符,将类的对象使用逻辑操作符进行逻辑运算会怎么样呢?
编程实验:重载逻辑运算符
// 26-2.cpp
#include<iostream>
using namespace std;
class Test
{
public:
Test(int v) : mValue(v){}
int value() const { return mValue; }
private:
int mValue;
};
bool operator && (const Test& t1, const Test& t2)
{
return t1.value() && t2.value();
}
bool operator || (const Test& t1, const Test& t2)
{
return t1.value() || t2.value();
}
Test func(Test i)
{
cout << "func(Test i) : i.value() = " << i.value() << endl;
return i;
}
int main()
{
Test t0(0);
Test t1(1);
if (func(t0) && func(t1))
{
cout << "Result is true" << endl;
}
else
{
cout << "Result is false" << endl;
}
if (func(t0) || func(t1))
{
cout << "Result is true" << endl;
}
else
{
cout << "Result is false" << endl;
}
}
代码中我们重载了逻辑操作符,对类的对象进行逻辑计算,前面我们说的短路规则还存在吗?
编译运行,用结果来检验
$ g++ 26-2.cpp -o 26-2
$ ./26-2
func(Test i) : i.value() = 1
func(Test i) : i.value() = 0
Result is false
func(Test i) : i.value() = 1
func(Test i) : i.value() = 0
Result is true
可以看到,逻辑操作符没有短路特性了,表达式 func(t0) && func(t1) 和 func(t0) || func(t1) 从结果看也是先计算 func(t1) 再计算 func(t1),这是怎么回事呢?
我们将上面的写法改变一下,使用重载的操作符本就是就是调用函数
- func(t0) && func(t1) 等同于 operator && (func(t0), func(t1)),这是一个函数调用
- func(t0) || func(t1) 等同于 operator || (func(t0), func(t1)),这也是一个函数调用
问题的本质:
- C++ 通过函数调用实现扩展操作符的功能
- 进入函数体之前必须完成所有参数的计算,短路法则失效
- 函数参数的计算次序是不定的
也就是说重载的操作符就是函数调用,没有短路特性了,和原生意义不一样了,重载不能改变操作符的原生意义,这怎么办呢?
建议如下:
- 避免重载逻辑操作符
- 通过重载比较操作符替换逻辑操作符重载
- 直接使用成员函数代替逻辑操作符重载
- 使用全局函数对逻辑操作符进行重载
3 小结
1、C++ 从语法上支持逻辑操作符重载,重载后不满足短路法则
2、实际工程开发不要重载逻辑操作符
3、通过重载比较操作符、使用专用的成员函数代替逻辑操作符重载
探讨C++中逻辑操作符(&&, ||)的原生行为与重载后的差异,详解短路法则失效原因及替代方案。
1034

被折叠的 条评论
为什么被折叠?



