用面向对象语言实现一个计算器控制台程序

 1 #include  < iostream >
 2 using   namespace  std;
 3 // Operation 运算类
 4 class  Operation {
 5    double m_numberA;
 6    double m_numberB;
 7public:
 8    void SetNumA(double numA) { m_numberA = numA;}
 9    void SetNumB(double numB) { m_numberB = numB;}
10    double GetNumA(voidconst return m_numberA;}
11    double GetNumB(voidconst return m_numberB;}
12    virtual double GetResult() = 0;
13}
;
14 class  OperationAdd: public  Operation {
15public:
16    double GetResult(){
17        return GetNumA() + GetNumB();
18    }

19}
;
20 class  OperationSub: public  Operation {
21public:
22    double GetResult(){
23        return GetNumA() - GetNumB();
24    }

25}
;
26 class  OperationMul: public  Operation {
27public:
28    double GetResult(){
29        return GetNumA() * GetNumB();
30    }

31}
;
32 class  OperationDiv: public  Operation {
33public:
34    double GetResult(){
35        if (GetNumB() == 0)
36            throw "numB cannot be zero!";        
37        return GetNumA() / GetNumB();
38    }

39}
;
40 class  OperationFactory {
41public:
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<GetNumA()<<' '<GetNumB()<<" = "<GetResult()<76    system("pause");
77    return 0;
78}

你可能感兴趣的:(c++,面向对象)