patterncppMinor
Calculator - C++ operator-overloading
Viewed 0 times
overloadingcalculatoroperator
Problem
I am new to object-oriented concepts. The following is my attempt at creating a basic calculator using class and operator overloading concepts. Please review it for improvements. Also, how do I make it more intuitive? I want to display:
+,-,*,/ as options and use switch on them. #include
#include
using namespace std;
class calculator
{
private:
float val;
public:
calculator(): val(0)
{}
void getdata()
{
cout > val;
}
void showdata()
{
cout > choice;
cout << endl;
switch (choice)
{
case 1:
obj3 = obj1 + obj2;
break;
case 2:
obj3 = obj1 - obj2;
break;
case 3:
obj3 = obj1 * obj2;
break;
case 4:
obj3 = obj1 / obj2;
break;
default:
cout << "Invalid choice! " << endl;
}
cout << "Result ";
obj3.showdata();
cout << endl;
}Solution
You can also overload
Similar approach with
operator>> instead of using getdata():std::istream& operator>>(std::istream& in, calculator& obj)
{
return in >> obj.val;
}Similar approach with
showdata(), using operator
- You don't appear to be using
, so just remove it.
- You don't need to use
std::endl in so many places. A simple "\n"` for outputting a newline should be sufficient. More info about that here.Code Snippets
std::istream& operator>>(std::istream& in, calculator& obj)
{
return in >> obj.val;
}std::ostream& operator<<(std::ostream& out, calculator const& obj)
{
return out << "value: " << obj.val;
}Context
StackExchange Code Review Q#79185, answer score: 5
Revisions (0)
No revisions yet.