简单工厂类实现运算器
#include <iostream>using namespace std;class Operation //运算类{private:double num1;double num2;public:Operation(){}double getNum1(){return num1;}...
·
#include <iostream>
using namespace std;
class Operation //运算类
{
private:
double num1;
double num2;
public:
Operation(){}
double getNum1()
{
return num1;
}
double getNum2()
{
return num2;
}
void setNum1(double x)
{
num1=x;
}
void setNum2(double x)
{
num2=x;
}
double virtual getResult()
{
return 0;
}
};
class OpAdd: public Operation//加法类
{
public:
double getResult()
{
double result=0;
result = getNum1()+getNum2();
return result;
}
};
class OpSub:public Operation//减法类
{
double getResult()
{
double result=0;
result = getNum1()-getNum2();
return result;
}
};
class OpMul:public Operation//乘法类
{
double getResult()
{
double result=0;
result = getNum1()*getNum2();
return result;
}
};
class OpDiv:public Operation// 除法类
{
double getResult()
{
double result=0;
if(getNum2()==0)
throw "除数不能为0";
else
result = getNum1()/getNum2();
return result;
}
};
class OpFactory//工厂类
{
public :
static Operation *createOperation(char operate)//因为这里使用的是多态,所以需要用指针
{
Operation *oper=NULL;//NULL需要大写
switch(operate)//switch需要是char类型的
{
case '+':
oper= new OpAdd();
break;
case '-':
oper=new OpSub();
break;
case '*':
oper=new OpMul();
break;
case '/':
oper=new OpDiv();
break;
}
return oper;
}
};
int main()
{
Operation *oper;//因为工厂类的返回值是一个指针
OpFactory of;
char op;
double x,y;
cin>>x>>op>>y;
oper =of.createOperation(op);
oper->setNum1(x);
oper->setNum2(y);
double result=oper->getResult();
cout<<result<<endl;
}
在c++中,子类想要重载父类的成员函数,需要先将 父类的成员函数声明为是一个虚函数。
多态的实现需要指针
更多推荐
已为社区贡献1条内容
所有评论(0)