</pre><pre name="code" class="cpp"><img src="https://img-blog.csdn.net/20160519203716268?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
</pre><pre name="code" class="cpp"><span style="font-size:18px;color:#ff0000;"><strong>一、先创建Operation.h</strong></span>
<span style="font-size:18px;">#pragma once
#include <iostream>
using namespace std;
class Operation {
private:
double _numberA = 0;
double _numberB = 0;
public:
double get_A(){ return _numberA; }
double get_B(){ return _numberB; }
void set_A(double value) { _numberA = value; }
void set_B(double value){ _numberB = value; }
virtual double GetResult(){
double result = 0;
return result;
};
};
class OperationAdd :public Operation
{
public:
double GetResult(){
double result = 0;
result = get_A() + get_B();
return result;
}
};
class OperationSub :public Operation
{
public:
double GetResult(){
double result = 0;
result = get_A() - get_B();
return result;
}
};
/// <summary>
///
/// </summary>
class OperationMul :public Operation
{
public:
double GetResult(){
double result = 0;
result = get_A() * get_B();
return result;
}
};
/// <summary>
///
/// </summary>
class OperationDiv :public Operation
{
public:
double GetResult(){
double result = 0;
if (get_B() == 0)
throw("除数不能为0");
result = get_A() / get_B();
return result;
}
};
/// <summary>
///
/// </summary>
class OperationFactory
{
public:
static Operation* createOperate(char operate) {
Operation *oper = NULL;
switch (operate) {
case 'a': {
oper = new OperationAdd();
break;
}
case 'b': {
oper = new OperationSub();
break;
}
case 'c': {
oper = new OperationMul();
break;
}
case 'd': {
oper = new OperationDiv();
break;
}
}
return oper;
}
};</span>
<span style="font-size:18px;">
</span>
<span style="font-size:18px;color:#ff0000;"><strong>二、在MainDlg.cpp添加事件处理函数</strong></span>
<span style="font-size:18px;">
</span>
<span style="font-size:18px;">void CCalculatorDlg::OnBnClickedButton3()
{
// TODO: 在此添加控件通知处理程序代码
UpdateData(TRUE);
Operation *oper = OperationFactory::createOperate('a');
oper->set_A(data1);
oper->set_B(data2);
data3 = oper->GetResult();
UpdateData(FALSE);
}
</span>
写出来感觉怪怪的,求哪位大神指点一下,这是我们的暑假考试作业
主要是那个工厂模式怎么写和调用问题。