Question
Let's try to develop a C++ Reverse Polish Notation (RPN) calculator! Create a base class called Operand Derive a class called Number from Operand -
Let's try to develop a C++ Reverse Polish Notation (RPN) calculator!
Create a base class called Operand
Derive a class called Number from Operand
- Maintain a double variable in class Number
- If you like, you can make the variable public for simplicity
Derive a class called Operator from Operand
- Derive a class called Add from Operator
- Derive a class called Subtract from Operator
- Derive a class called Multiply from Operator
- Derive a class called Divide from Operator
Almost all of the above classes are going to be empty
- Only class Number will have a true constructor and member variables
- If you wish you can put all of these classes into a file called Operands.h
Develop some C++ code that does the following:
- Create a queue of Operand pointers
- Use push_back operations to build the stack just like you would using RPN
- Develop a function called Calculate which takes in a stack and returns the double result
The Calculate() function must do the following:
- For each element of the queue starting at the front:
+ If the operand is a Number, add it to a stack
+ If the operand is an Operator, pop two values off the stack and use that operator to do the correct math, then put the new value back on the stack
= You'll need to use dynamic_cast to make this work
- When things complete, the stack should hold the final result. Return it.
Example:
std::queue a;
a.push_back(new Number(1));
a.push_back(new Number(2));
a.push_back(new Add());
std::cout << Calculate(a); // Prints 3
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started