Advertisement
Guest User

help

a guest
Oct 17th, 2019
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.54 KB | None | 0 0
  1. Let's try to develop a C++ Reverse Polish Notation (RPN) calculator!
  2. Create a base class called Operand
  3. Derive a class called Number from Operand
  4. • Maintain a double member variable in class Number
  5. • For simplicity, you may make the member variable public if you would like
  6. Derive a class called Operator from Operand
  7. Derive a class called Add from Operator (2 + 3 = 5)
  8. Derive a class called Subtract from Operator (5 - 2 = 3)
  9. Derive a class called Multiply from Operator (5 * 3 = 15)
  10. Derive a class called Divide from Operator (18 / 6 = 3)
  11. Derive a class called Square from Operator (3^2 = 9)
  12. Almost all of the above classes are going to be "empty" classes
  13. • As described above, only class Number will have a true constructor with a member variable and member functions
  14. • Everything else will actually be empty! Like seriously empty!
  15. • If you wish you can put all of the classes described above into a single file called Operands.h
  16. In a separate file, create a function called Calculate() that must do the following:
  17. • The only input parameter is a std::queue of Operand pointers (the series of number values and operations that will be performed by the calculator)
  18. • Use an std::stack of double values internally to maintain the numeric value stack throughout the execution of the function
  19. • For each element of the queue, starting from the front:
  20. o If the operand is a Number, simply add its value to the stack
  21. o If the operand is an Operator, pop one or two values off the stack (depends on which of the five operators) and use that operator to do the correct math, then put the new value back on the stack
  22.  You'll need to use the dynamic_cast keyword to make this work correctly
  23.  If you don't correctly set up the calculation code, the stack might become empty too soon. Throw an exception of some kind if this happens.
  24. • When things complete, the stack should only hold the final result value. Return it from the function.
  25. Develop some C++ code in the main() function that uses your Calculate() function by doing the following:
  26. • Watch this video for the calculation I want to see computed by your program
  27. • Create a queue of Operand pointers
  28. • Use push_back operations to build the stack just like you would using RPN
  29. • Call Calculate() with the queue
  30. • In this case, print 11 by using the video as your template (by using code like you see below)
  31. Simpler Example Code:
  32. std::queue<Operand *> a;
  33. a.push_back(new Number(1));
  34. a.push_back(new Number(2));
  35. a.push_back(new Add());
  36. std::cout << Calculate(a); // Prints 3
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement