本文共 2756 字,大约阅读时间需要 9 分钟。
std::string method_type;std::cout << "calc program is start,please input calc method type:" << std::endl;std::cin >> method_type;std::cout << "please input calc num1:" << std::endl;double obj1(0), obj2(0);std::cin >> obj1;std::cout << "please input calc num2:" << std::endl;std::cin >> obj2;double result(0);if(method_type == "+"){ result = obj1 + obj2;}else if(method_type == "-"){ result = obj1 - obj2;}else if(method_type == "*"){ result = obj1 * obj2;}else if(method_type == "/"){ result = obj1 / obj2;}else{std::cout << "not valid input method!\n";} std::cout << "result is: " << result << std::endl;诚然这样的代码简单直接,但是这样的代码它带来的可维护性、扩展性、代码复用率不高,因而是很有局限的。因而需要在此基础上对其进行封装和改进。下面就将讲到使用到的方法:继承和多态(它的原理将在下面说明)
请参考博文:
#include#include #include #include #include "chapter1.h"int main(void){ std::string method_type; std::cout << "calc program is start,please input calc method type:" << std::endl; std::cin >> method_type; std::cout << "please input calc num1:" << std::endl; double obj1(0), obj2(0); std::cin >> obj1; std::cout << "please input calc num2:" << std::endl; std::cin >> obj2; GetResult(method_type, obj1, obj2); return 0;}
#pragma once#include#include #include //基类template class BaseOpterator{public: T m_result;public: virtual void Calc(T obj1, T obj2) { this->m_result = 0; } void DisPlay() { std::cout << "result is: " << this->m_result << std::endl; }};//派生出来的加法类template class AddOpterator: public BaseOpterator {public: void Calc(T obj1, T obj2) override { this->m_result = obj1 + obj2; }};//派生出来的减法类template class SubOpterator: public BaseOpterator {public: void Calc(T obj1, T obj2) override { this->m_result = obj1 - obj2; }};//派生出来的乘法类template class MulOpterator: public BaseOpterator {public: void Calc(T obj1, T obj2) override { this->m_result = obj1 * obj2; }};//派生出来的除法类template class DevOpterator: public BaseOpterator {public: void Calc(T obj1, T obj2) override { this->m_result = obj1 / obj2; }};//计算输入的数据template GetResult(std::string method_type, T obj1, T obj2){ BaseOpterator * base; if(method_type == "+") { base = new AddOpterator (); } else if(method_type == "-") { base = new SubOpterator (); } else if(method_type == "*") { base = new MulOpterator (); } else if(method_type == "/") { base = new DevOpterator (); } else{std::cout << "not valid input method!\n";} //得到计算结果 base->Calc(obj1, obj2); base->DisPlay(); delete base; base = nullptr;}
转载地址:http://cykhj.baihongyu.com/