factory.h
#ifndef FACTORY_H #define FACTORY_H #include "operate.h" // virtual double operate(double, double) = 0; class Factory { public: virtual void Create(void) = 0; protected: Operate *op; private: }; class AddFactory: public Factory { public: void create(void ) { op = new AddOperate; } private: }; class SubFactory: public Factory { public: Operate* create(void ) { op = new SubOperate; } private: }; #endif
operate.h
#ifndef OPERATE_H #define OPERATE_H class Operate { public: virtual double operate(double, double) = 0; private: double m_num1; double m_num2; }; class AddOperate: public Operate { double operate(double a, double b) { return a+b; } }; class SubOperate: public Operate { double operate(double a, double b) { return a-b; } }; #endif
main.cpp
#include <iostream> #include "operate.h" #include <string> #include "factory.h" int main() { char s1; std::cout << "input" << std::endl; std::cin >> s1 ; // Operate *oper ;//= new AddOperate; // Factory *fact = new AddFactory; Operate *oper = new AddOperate; switch(s1) { case '+' : // Factory *fact = new AddFactory; break; case '-': // Factory fact = new SubFactory; break; default : // Factory fact = new AddFactory; break; } /* Operate *oper = fact.Create(); std::cout << oper->operate(2,3) << std::endl; */ return 0; }