1) 定义工厂对象和其他的计算对象或指针,需要先有对象空间,分配对象之后才能对其操作, Operation *oper = NULL; FactorayCreate factory; oper =factory.CreateCompute('/');只是有指针是不行的,数据不会分配空间,报错。
Operation.h
#ifndef _OPERATION_H_
#define _OPERATION_H_
#include <iostream>
using namespace std;
//template <class T>
class Operation
{
public:
// Operation(){}
// ~Operation(){}
virtual double GetResult(){return 0;}
void SetNumberA(double a) { NumA = a;}
void SetNumberB(double b) { NumB = b;}
protected:
double NumA;
double NumB;
};
class OperationAdd : public Operation
{
public:
// OperationAdd(){};
// ~OperationAdd(){}
double GetResult(){return (NumA+NumB);}
};
class OperationSub : public Operation
{
public:
OperationSub(){}
~OperationSub(){}
double GetResult(){return (NumA-NumB);}
};
class OperationDiv : public Operation
{
public:
OperationDiv(){}
~OperationDiv(){}
double GetResult(){
if(NumB == 0)return 0;
return (NumA/NumB); }
};
class OperationMul : public Operation
{
public:
OperationMul(){}
~OperationMul(){}
double GetResult(){ return (NumA*NumB);}
};
class FactorayCreate
{
public:
FactorayCreate(){}
~FactorayCreate(){}
Operation *CreateCompute(char op)
{
switch(op)
{
case '+': c = op;
oper = new OperationAdd();
break;
case '-': oper = new OperationSub(); break;
case '/': oper = new OperationDiv(); break;
case '*': oper = new OperationMul(); break;
default: oper = new OperationMul(); break;
}
return oper;
}
private:
Operation *oper;
char c ;
};
#endif//~_OPERATION_H_
main
#include "stdafx.h"
#include "Operation.h"
int main(int argc, char* argv[])
{
Operation *oper = NULL;
FactorayCreate factory;
oper = factory.CreateCompute('/');
oper->SetNumberA(3);
oper->SetNumberB(0);
cout<<oper->GetResult()<<endl;
return 0;
}