Explore BrainMass

Impletation of a Calculator Class in C++

The main function is provided that will create an object of the calculator class and calling methods from this object. The calculator class definition will have to be defined in the "calculator.h" file. The class should have the prototypes for all the methods called in the "main" function and a private double variable for holding the running answer ("ans"). The implementation for the methods should be in a separate "calculator.cpp" file.All the methods (add, sub, ....) modify the private answer "ans" variable in the class object. The print_ans() method should be exclusively used in the other methods for printing the answer to the screen. Each addition, subtraction, division, and multiplication method should also output to the screen which numbers are being operated on and which operation is performed.

Overloaded methods for the operations of adding, subtracting, multiplication, and division will need to be created requiring one or two arguments. The single argument is added to, subtracted from, divided over, or multiplied by the running answer. The "main" function should clarify which overloaded methods should be generated. The main function shouldn't need altering, hopefully.


Solution Preview

Creating a class in C++ usually involves defining the class methods and data in a header file (i.e. "*.h") and providing the implementation for all of the methods in an implementation file (i.e. "*.cpp"). For this solution we have created a C++ class to implement the four calculator functions +, -, *, /. Each function can operator on either one or two operands. The answer from the operation is stored in an internal variable so that it can be modified in future operations.

The class ...

Solution Summary

This solutions provides a clear and easy to understand example of creating a simple calculator in C++. It uses a single C++ class to represent the calculator. The solution focuses on how to define and use a class. In particular, it shows how to put the class definition in a header file and the implementation in a cpp file. It also shows how to define overloaded methods in a class.