C++实现简单计算器:使用函数指针和Map
C++实现简单计算器:使用函数指针和Map
以下示例代码展示了如何使用 C++ 实现一个简单计算器,利用函数指针和 std::map 实现更优雅的操作符映射:cpp#include
using namespace std;
// 加法函数double add(double num1, double num2) { return num1 + num2;}
// 减法函数double subtract(double num1, double num2) { return num1 - num2;}
// 乘法函数double multiply(double num1, double num2) { return num1 * num2;}
// 除法函数double divide(double num1, double num2) { if (num2 == 0) { throw runtime_error('除数不能为零'); } return num1 / num2;}
// 计算器类class Calculator {private: map<string, function<double(double, double)>> operators;
public: Calculator() { // 注册操作符和对应的函数 operators['+'] = add; operators['-'] = subtract; operators['*'] = multiply; operators['/'] = divide; }
double calculate(double num1, double num2, string oper) { if (operators.find(oper) == operators.end()) { throw runtime_error('不支持的操作符'); }
// 通过操作符查找对应的函数,并进行计算 function<double(double, double)> operation = operators[oper]; return operation(num1, num2); }};
int main() { double firstP, secondP; string oper;
cout << '请输入操作数1:'; cin >> firstP; cout << '请输入操作数2:'; cin >> secondP; cout << '请输入操作:'; cin >> oper;
Calculator calculator; try { double result = calculator.calculate(firstP, secondP, oper); cout << firstP << ' ' << oper << ' ' << secondP << ' = ' << result << endl; } catch (const exception& e) { cout << '发生错误:' << e.what() << endl; }
return 0;}
这段代码的核心在于:
- 使用函数指针:
function<double(double, double)>定义了可以存储指向接受两个double参数并返回double值的函数的指针。- 利用std::map映射操作符:map<string, function<double(double, double)>> operators创建了一个映射,将字符串形式的操作符('+', '-', '*', '/') 与对应的函数指针关联起来。
优点:
- 代码简洁易懂,易于扩展新的操作符和功能。- 通过
std::map实现操作符与函数的清晰映射。
缺点:
- 需要手动处理除零错误。- 没有使用面向对象的方式封装操作符和函数,可能不够灵活。
注意事项:
这只是一个简单的示例实现,实际应用中还需要考虑更完善的错误处理、输入验证等细节。
原文地址: https://www.cveoy.top/t/topic/bxoq 著作权归作者所有。请勿转载和采集!