逻辑运算符
1)&&和||是C++中非常特殊的操作符
2)&&和||内置实现了短路规则
3)操作符重载是靠函数重载来完成的
4)操作数作为函数参数传递
5)C++的函数参数都会被求值,无法实现短路规则
#include <iostream>
using namespace std;
class Test8_1
{
friend ostream &operator<< (ostream &out, const Test8_1 &t);
public:
Test8_1(int t = 0)
{
this->t = t;
}
bool operator &&(Test8_1 &obj)
{
return this->t && obj.t;
}
private:
int t;
};
ostream &operator<< (ostream &out, const Test8_1 &t)
{
out << t.t;
return out;
}
int main()
{
int a = 0;
int b = 2;
int c = 3;
// 逻辑运算符的短路规则:
// || 有一个表达式为真,后面的表达式将不再执行
// && 有一个表达式为假,后面的表达式将不再执行
a || (b = c);
a && (b = c);
printf ("a = %d, b = %d, c = %d\n", a, b, c);
Test8_1 t1(0), t2(1), t3(2);
// bool operator &&(Test8_1 &t1, Test8_1 &t2); ===> bool operator &&(Test8_1 &t2);
// t1.operator&& (t2 = t3)
// 逻辑运算符重载无法实现短路运算规则
t1 && (t2 = t3);
cout << t1 << endl;
cout << t2 << endl;
cout << t3 << endl;
return 0;
}
执行结果:
a = 0, b = 3, c = 3
0
2
2
本文探讨了C++中逻辑运算符(&&和||)的特殊性及其短路规则,并通过实例展示了如何进行操作符重载,同时指出重载后的逻辑运算符无法实现短路效果。
3834

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



