# c++写一个计算器程序

1.1设计一个父类Operation, 数据成员包含两个操作数m_numberA，m_numberB。 成员函数包括set(),get()函数设置操作数的值，虚函数GetResult()用于输出结果。

1.3派生类统一继承自父类Operation, 重写虚函数GetResult()输出操作后的结果。

1.4 OperationFactory类已经写好，可以直接使用。
class OperationFactory {

public:

static Operation * CreateOperate(char oper)

{

``````   Operation * poper = NULL;

switch (oper)

{

case '+':

break;

case '-':

poper = new OperationSub;

break;

case '*':

poper = new OperationMul;

break;

case '/':

poper = new OperationDiv;

break;

}

return poper;

}
``````

};

int main()

{

``````   int flag = 1;

while (flag)

{

cout << "input A:";

double numA;

cin >> numA;

cout << "input operator:";

char oper;

cin >> oper;

cout << "input B:";

double numB;

cin >> numB;

Operation* poper = OperationFactory::CreateOperate(oper);

poper->SetNumA(numA);

poper->SetNumB(numB);

cout << poper->GetNumA() << ' ' << oper << ' ' << poper->GetNumB() << " = " << poper->GetResult() << endl;

cout << "是否需要继续: (0/1)";

cin >> flag;

}

return 0;
``````

}

• 写回答

#### 2条回答默认 最新

关注
``````class Operation
{
double m_numberA,m_numberB;
public:
double GetNumA() {return m_numberA;}
double GetNumB() {return m_numberB;}
void SetNumA(double A) {m_numberA = A;}
void SetNumB(double B) {m_numberB = B;}
virtual double GetResult() {return 0;}
};

{
public:
virtual double GetResult() {return GetNumA() + GetNumB();}
};

class OperationSub : public Operation
{
public:
virtual double GetResult() {return GetNumA() - GetNumB();}
};

class OperationMul : public Operation
{
public:
virtual double GetResult() {return GetNumA() * GetNumB();}
};

class OperationDiv : public Operation
{
public:
virtual double GetResult() { if(GetNumB() == 0) return 0; return GetNumA() / GetNumB();}
};

class OperationFactory {
public:

static Operation * CreateOperate(char oper)

{

Operation * poper = NULL;

switch (oper)

{

case '+':

break;

case '-':

poper = new OperationSub;

break;

case '*':

poper = new OperationMul;

break;

case '/':

poper = new OperationDiv;

break;

}

return poper;

}
};

int main()

{
int flag = 1;

while (flag)

{

cout << "input A:";

double numA;

cin >> numA;

cout << "input operator:";

char oper;

cin >> oper;

cout << "input B:";

double numB;

cin >> numB;

Operation* poper = OperationFactory::CreateOperate(oper);

poper->SetNumA(numA);

poper->SetNumB(numB);

cout << poper->GetNumA() << ' ' << oper << ' ' << poper->GetNumB() << " = " << poper->GetResult() << endl;

cout << "是否需要继续: (0/1)";

cin >> flag;

}

return 0;
}

``````
本回答被题主选为最佳回答 , 对您是否有帮助呢?
评论 编辑记录

• 系统已结题 4月19日
• 已采纳回答 4月11日
• 创建了问题 4月11日

#### 悬赏问题

• ¥15 电脑锁屏时vba运行SAP,excel数据不能复制到SAP
• ¥50 74LS系列 74LS00 74LS04设计一个RS485电路(关键词-差分)
• ¥30 各位help写一下代码
• ¥15 在运行SDEdit模型下载不了
• ¥15 求51控制l298n驱动的小车中超声波避障怎么写
• ¥15 电脑连上WIFI却用不了
• ¥30 MATLAB在RLC电路的固有响应和阶跃响应GUI仿真报告
• ¥15 hyper-v出现的问题
• ¥15 有能用的可加酬金，求可以批量下载懒人听书的软件，能登录自己帐号的。
• ¥100 高博一起做RGB-D SLAM（5）VO无法出visualisation问题