#include #include using namespace std;
int func(int i)
int main()
else
cout << endl;
if( func(1) || func(0) )
else
return 0;
}
邏輯操作符可以過載嗎? 過載邏輯操作符有什麼意義?輸出:【短路法則】
int func(int i) : = 0
result is false!
int func(int i) : = 1
result is true!
#include #include using namespace std;
class test
int value() const
};bool operator && (const test& l, const test& r)
bool operator || (const test& l, const test& r)
test func(test i)
int main()
else
cout << endl;
if( func(1) || func(0) ) // 注意這裡!
else
return 0;
}
輸出:
test func(test i) : i.value() = 1
test func(test i) : i.value() = 0
result is false!
test func(test i) : i.value() = 0
test func(test i) : i.value() = 1
result is true!
分析:過載後的邏輯操作符為什麼沒有按照短路法則執行呢?
if( func(t0) && func(t1) ) {}
if( func(t0) || func(t1) ) {}
邏輯操作符過載後無法完全實現原生的語義!!if( operator && (func(t0), func(t1)) ) {}
if( operator || (func(t0), func(t1)) ) {}
38 邏輯操作符的陷阱
邏輯操作符的原生語義 運算元只有兩種值 true和false 邏輯表示式不用完全計算就能確定最終值,最終結果只能是true或者false。邏輯操作符可以過載嗎?include include using namespace std int func int i int main else cout ...
第38課 邏輯操作符的陷阱
1.1 運算元只有兩種值 true和false 1.2 邏輯表示式不用完全計算就能確定最終值 1.3 最終結果只能是true或false 邏輯表示式 又叫短路表示式 include using namespace std int func int i int main else cout endl ...
邏輯操作符的陷阱
運算元只有兩種值 true和false 邏輯表示式不用完全計算就能確定最終值 最終結果只能是true或者false 那麼,如果我們過載邏輯運算子會發生什麼?例 1 include 2 include 3using namespace std 4class test 512 test 1315 int...