您的位置:首页 > 编程语言 > C语言/C++

大话设计模式 工厂模式 C++计算器

2017-03-24 21:54 148 查看
#include<iostream>

using namespace std;

class Operation
{
public:
    virtual double getAnswer(double _num1 ,double _num2) = 0;
};
class OperationAdd : public Operation
{
public:
    double getAnswer(double _num1,double _num2)
    {
        return _num1 + _num2;
    }
};
class OperationSub : public Operation
{
public:
     double getAnswer(double _num1,double _num2)
    {
        return _num1 - _num2;
    }
};
class OperationDiv : public Operation
{
public:
     double getAnswer(double _num1,double _num2)
    {
        return _num1 / _num2;
    }
};
class OperationMul : public Operation
{
public:
     double getAnswer(double _num1,double _num2)
    {
        return _num1 * _num2;
    }
};
class CFactory
{
public:
    Operation & creatFactory(char type)
    {
        Operation *op;
        switch(type)
        {
        case '+':
        op = new OperationAdd();
        break;
         case '-':
        op = new OperationSub();
        break;
         case '*':
        op = new OperationMul();
        break;
         case '/':
        op = new OperationDiv();
        break;
        }
        return * op;
    }
};
int main()
{
    CFactory factory;
    Operation *op;
    double num1,num2;
    char type;
    cin >> num1 >> type >> num2;
    op = &factory.creatFactory(type);
    cout << op->getAnswer(num1,num2);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: