C++ 简单工厂模式实现加减运算
#include
class Operator { protected: int firstParameter; int secondParameter; public: Operator(int firstP, int secondP) : firstParameter(firstP), secondParameter(secondP) {} virtual int getResult() = 0; };
class Add : public Operator { public: Add(int firstP, int secondP) : Operator(firstP, secondP) {} int getResult() override { return firstParameter + secondParameter; } };
class Sub : public Operator { public: Sub(int firstP, int secondP) : Operator(firstP, secondP) {} int getResult() override { return firstParameter - secondParameter; } };
class OperatorSimpleFactory { public: static Operator* createOperator(std::string oper, int firstP, int secondP) { if (oper == '+') { return new Add(firstP, secondP); } else { return new Sub(firstP, secondP); } } };
int main() { std::string oper = ""; int firstP; int secondP; std::cout << "请输入想要进行的操作:" << std::endl; std::cin >> oper; std::cout << "请输入操作数1:" << std::endl; std::cin >> firstP; std::cout << "请输入操作数2:" << std::endl; std::cin >> secondP; Operator* op = OperatorSimpleFactory::createOperator(oper, firstP, secondP); std::cout << op->getfirstP() << oper << op->getsecondP() << "=" << op->getResult() << std::endl; std::cout << "运行结束" << std::endl; return 0; }
原文地址: https://www.cveoy.top/t/topic/bxvc 著作权归作者所有。请勿转载和采集!