C++面向对象编程实例
实例一、四位运算符操作
main.cpp.
1 #include <iostream> 2 #include "operator_1.h" 3 #include <stdio.h> 4 #include <iomanip> 5 6 using namespace std; 7 8 int main() 9 { 10 double r = 0; 11 operator_1 op; 12 13 op.setOperator_1('*'); 14 op.setOperator_1Parameter(100.0, 3.0); 15 16 if (op.result(r)){ 17 cout<<setiosflags(ios::fixed)<<r<<endl;//位数不够,末尾添0 18 } 19 else { 20 cout <<"calculate erro!" << endl; 21 } 22 23 return 0; 24 }
operator_1.cpp
1 #include "operator_1.h" 2 3 bool operator_1::setOperator_1(char op){ 4 bool ret = false; 5 if((op == '*')||(op == '/')||( op == '+')||( op == '*')){ 6 ret == true; 7 op_1 =op; 8 } 9 else { 10 return ret; 11 } 12 } 13 14 void operator_1::setOperator_1Parameter(double a, double b){ 15 m0p = a; 16 m1p = b; 17 } 18 19 bool operator_1::result(double & r){ 20 bool ret = true; 21 switch (op_1) { 22 case '+': 23 r = m0p + m1p; 24 break; 25 case '-': 26 r = m0p - m1p; 27 break; 28 case '*': 29 r = m0p * m1p; 30 break; 31 case '/': 32 r = m0p / m1p; 33 break; 34 default: 35 return ret= false; 36 break; 37 } 38 }
operator_1.h
1 #ifndef OPERATOR_H 2 #define OPERATOR_H 3 4 class operator_1 5 { 6 public: 7 bool setOperator_1(char op); 8 void setOperator_1Parameter(double a, double b); 9 bool result(double & r); 10 private: 11 double m0p; 12 double m1p; 13 char op_1; 14 }; 15 #endif // OPERATOR_H