#include <iostream>
#include <string>
// TODO: Define a typedef 'MathOp' for a function pointer returning int, taking (int, int)
// typedef ... MathOp ...;
// OR: using MathOp = ...;
using MathOp = int (*)(int,int);
int add(int a, int b) { return a + b; }
int multiply(int a, int b) { return a * b; }
class Calculator {
private:
// TODO: Declare member variable 'current_op' of type MathOp
// Initialize it to 'add'
MathOp current_op = add;
public:
// TODO: Implement setMode
void setMode(MathOp op) {
current_op = op;
}
void compute(int a, int b) {
// TODO: Call the function pointer
if ( current_op != nullptr)
{
int res = current_op(a,b);
std::cout << "Result: " << res << std::endl;
}
}
};
int main() {
Calculator calc;
int N;
if (!(std::cin >> N)) return 0;
for (int i = 0; i < N; ++i) {
std::string cmd;
std::cin >> cmd;
if (cmd == "MODE_ADD") {
calc.setMode(add);
} else if (cmd == "MODE_MUL") {
calc.setMode(multiply);
} else if (cmd == "CALC") {
int a, b;
std::cin >> a >> b;
calc.compute(a, b);
}
}
return 0;
}
Input
3 CALC 10 10 MODE_MUL CALC 10 10
Expected Output
Result: 20 Result: 100