用面向對象語言實現一個計算器控制臺程序
1
#include <iostream>
2
using namespace std;
3
//Operation 運算類
4
class Operation{
5
double m_numberA;
6
double m_numberB;
7
public:
8
void SetNumA(double numA) { m_numberA = numA;}
9
void SetNumB(double numB) { m_numberB = numB;}
10
double GetNumA(void) const { return m_numberA;}
11
double GetNumB(void) const { return m_numberB;}
12
virtual double GetResult() = 0;
13
};
14
class OperationAdd:public Operation{
15
public:
16
double GetResult(){
17
return GetNumA() + GetNumB();
18
}
19
};
20
class OperationSub:public Operation{
21
public:
22
double GetResult(){
23
return GetNumA() - GetNumB();
24
}
25
};
26
class OperationMul:public Operation{
27
public:
28
double GetResult(){
29
return GetNumA() * GetNumB();
30
}
31
};
32
class OperationDiv:public Operation{
33
public:
34
double GetResult(){
35
if (GetNumB() == 0)
36
throw "numB cannot be zero!";
37
return GetNumA() / GetNumB();
38
}
39
};
40
class OperationFactory{
41
public:
42
static Operation* CreateOperate(char oper){
43
Operation *poper = NULL;
44
switch (oper){
45
case '+':
46
poper = new OperationAdd;
47
break;
48
case '-':
49
poper = new OperationSub;
50
break;
51
case '*':
52
poper = new OperationMul;
53
break;
54
case '/':
55
poper = new OperationDiv;
56
break;
57
}
58
return poper;
59
}
60
};
61
int main()
62
{
63
cout<<"input A:";
64
double numA;
65
cin>>numA;
66
cout<<"input operator:";
67
char oper;
68
cin>>oper;
69
cout<<"input B:";
70
double numB;
71
cin>>numB;
72
Operation *poper = OperationFactory::CreateOperate(oper);
73
poper->SetNumA(numA);
74
poper->SetNumB(numB);
75
cout<<poper->GetNumA()<<' '<<oper<<' '<<poper->GetNumB()<<" = "<<poper->GetResult()<<endl;
76
system("pause");
77
return 0;
78
}

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

posted on 2011-08-12 14:18 Hsssssss 閱讀(661) 評論(1) 編輯 收藏 引用 所屬分類: C++代碼