#ifndef ARITHOPERATOR_H
#define ARITHOPERATOR_H
#define EPS 0.000000000001
class ArithOpe
{
public:
virtual double GetArithOpeResult()const
{
return 0.0;
}
double GetArithOpeNum1()const
{
return this->m_num1;
}
double GetArithOpeNum2()const
{
return this->m_num2;
}
void SetArithOpeNum1(const double& num1)
{
this->m_num1=num1;
}
void SetArithOpeNum2(const double& num2)
{
this->m_num2=num2;
}
private:
double m_num1;
double m_num2;
};
class ArithOpeAdd:public ArithOpe
{
double GetArithOpeResult()const
{
return this->GetArithOpeNum1()+this->GetArithOpeNum2();
}
};
class ArithOpeSub:public ArithOpe
{
double GetArithOpeResult()const
{
return this->GetArithOpeNum1()-this->GetArithOpeNum2();
}
};
class ArithOpeMul:public ArithOpe
{
double GetArithOpeResult()const
{
return this->GetArithOpeNum1()*this->GetArithOpeNum2();
}
};
class ArithOpeDiv:public ArithOpe
{
double GetArithOpeResult()const
{
double tmp=this->GetArithOpeNum2()-(int)(this->GetArithOpeNum2());
if(tmp>=-EPS&&tmp<=EPS)
return 0.0;
return this->GetArithOpeNum1()/this->GetArithOpeNum2();
}
};
class ArithOpeMod:public ArithOpe
{
double GetArithOpeResult()const
{
double tmp=this->GetArithOpeNum2()-(int)(this->GetArithOpeNum2());
if(tmp>=-EPS&&tmp<=EPS)
return 0.0;
return (int)(this->GetArithOpeNum1())%(int)(this->GetArithOpeNum2());
}
};
#endif // ARITHOPERATOR_H
//simply Facotory
#ifndef FACTORY_H
#define FACTORY_H
#include "arithoperator.h"
class ArithOperatorFactory
{
public:
ArithOpe* CreateArithOperator(const char chsrc)
{
ArithOpe* pObject;
switch(chsrc)
{
case '+':
pObject = new ArithOpeAdd;
break;
case '-':
pObject = new ArithOpeSub;
break;
case '*':
pObject = new ArithOpeMul;
break;
case '/':
pObject = new ArithOpeDiv;
break;
case '%':
pObject = new ArithOpeMod;
break;
}
return pObject;
}
};
#endif // FACTORY_H
#include <stdio.h>
#include "factory.h"
int main(int argc, char *argv[])
{
ArithOperatorFactory Factory;
ArithOpe *pObj=Factory.CreateArithOperator('/');
pObj->SetArithOpeNum1(1.1);
pObj->SetArithOpeNum2(0);
printf("%0.2f\n", pObj->GetArithOpeResult());
return 0;
}