国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

第三十八課:邏輯操作符的陷阱----------狄泰軟件學(xué)院

2019-11-14 12:25:14
字體:
供稿:網(wǎng)友

一、邏輯運算符的原生語義

1.操作符只有兩種值(true和false) 2.邏輯表達(dá)式不用完全計算就能確定最終值 3.最終結(jié)果只能是true或者false

#include<iostream>using namespace std;int fun(int i){ cout<<"int fun(int i): i="<<i<<endl; return i;}int main(){ if(fun(0) && fun(1)) { cout<<"the result is true"<<endl; } else { cout<<"the result is false"<<endl; } cout<<endl; if(fun(0) || fun(1)) { cout<<"the result is true"<<endl; } else { cout<<"the result is false"<<endl; } return 0;}打印結(jié)果:int fun(int i): i=0the result is falseint fun(int i): i=0int fun(int i): i=1the result is true

二、重載邏輯操作符

#include<iostream>using namespace std;class Test{PRivate: int i;public: Test(int i) { this->i = i; } int getI() const { return i; }};bool Operator && (const Test& l, const Test& r){ return (l.getI() && r.getI());}bool operator || (const Test& l, const Test& r){ return (l.getI() || r.getI()); }Test fun(Test i){ cout<<"Test fun(Test i): i="<<i.getI()<<endl; return i;}int main(){ Test t0(0); Test t1(1); if(fun(t0) && fun(t1))//operator && (fun(t0), fun(t1)) 則先要算出參數(shù)fun(t0)和fun(t1)的值,且這兩個的計算順序不確定 { cout<<"the result is true"<<endl; } else { cout<<"the result is false"<<endl; } if(fun(t0) || fun(t1)) { cout<<"the result is true"<<endl; } else { cout<<"the result is false"<<endl; } return 0;}打印結(jié)果:Test fun(Test i): i=1Test fun(Test i): i=0the result is falseTest fun(Test i): i=1Test fun(Test i): i=0the result is true

問題本質(zhì)分析:

1.c++通過函數(shù)調(diào)用擴(kuò)展操作符的功能 2.進(jìn)入函數(shù)體前必須完成所有參數(shù)的計算 3.函數(shù)參數(shù)的計算次序是不確定的 4.短路法則完全失效 所以說邏輯操作符重載后無法完全實現(xiàn)原生語義

建議:

1.實際工程開發(fā)中避免重載邏輯操作符 2.通過重載比較操作符代替邏輯操作符重載 3.直接使用成員函數(shù)代替邏輯操作符重載 4.直接使用全局函數(shù)對操作符進(jìn)行重載

小結(jié):

1.c++在語法上支持邏輯操作符的重載 2.重載邏輯操作符后不滿足短路法則 3.通過重載比較操作符代替邏輯操作符重載 4.通過專用成員函數(shù)代替邏輯操作符


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 五原县| 吉安市| 玉树县| 鸡西市| 安宁市| 搜索| 运城市| 阜新市| 许昌市| 平舆县| 虞城县| 高青县| 乳山市| 静乐县| 阿鲁科尔沁旗| 家居| 屯门区| 哈密市| 洞口县| 黔东| 乃东县| 汨罗市| 伊吾县| 张北县| 重庆市| 宁波市| 泸州市| 丘北县| 岑溪市| 太原市| 儋州市| 南乐县| 高淳县| 阜南县| 本溪| 淮南市| 鄂州市| 清远市| 沙雅县| 枣强县| 常熟市|