C++設計模式-面向物件程式設計要點以及封裝性特點
阿新 • • 發佈:2018-11-17
目錄
1.面向物件程式設計要點
面向物件程式設計要注意什麼:
注意3點:
1.可維護性;
2.可擴充套件性;
3.可複用性;
4.靈活性好;
注意:要儘可能的避免重複;
要求業務邏輯與介面分離,讓他們的耦合性降低。只有這樣才能達到容易維護和擴充套件;
1.通過封裝、繼承、多型把程式的耦合度降低;
2.面向物件要結合設計模式使用,從而使得程式更加靈活,容易修改,並易於複用;
2.單使用封裝性的例子
單使用封裝性的面向物件程式設計:
執行截圖如下:
原始碼如下:
Operation.h
#include <iostream> #include <string> #include <cmath> using namespace std; class Operation{ public: static double getResult(double numberA, double numberB, string operate){ double result = 0.0; enum operation { addOper, subOper, mulOper, divOper }; if(operate.compare("+") == 0){ result = numberA + numberB; } else if(operate.compare("-") == 0){ result = numberA - numberB; } else if(operate.compare("*") == 0){ result = numberA * numberB; } else if(operate.compare("/") == 0){ if(abs(numberB) < 0.0001) throw "Division by zero condition!"; result = numberA / numberB; } else{ throw "The operator is wrong!"; } return result; } };
main.cpp
#include "Operation.h" int main(){ try{ double numberA, numberB; string opera; cout << "請輸入數字A:"; cin >> numberA; cout << "輸入運算子(+、-、*、/):"; cin >> opera; cout << "請輸入數字B:"; cin >> numberB; double result = Operation::getResult(numberA, numberB, opera); cout << result << endl; } catch(const char *msg){ cout << "error informaiton:" << msg <<endl; } system("pause"); return 0; }