Your question, your audience. Choose who sees your identityâ€”and your questionâ€”with question security.
#include <iostream>
#include <string>
struct Maths
{
virtual char const * action() const = 0;
virtual int operator()(int lhs_, int rhs_) const = 0;
};
struct Add : Maths
{
char const * action() const { return "+"; };
int operator()(int lhs_, int rhs_) const
{
return lhs_ + rhs_;
}
};
struct Sub : Maths
{
char const * action() const { return "-"; };
int operator()(int lhs_, int rhs_) const
{
return lhs_ - rhs_;
}
};
void DoMaths(Maths const & maths)
{
int lhs = 0;
int rhs = 0;
std::cout << "Enter first number: ";
std::cin >> lhs;
std::cout << "Enter second number: ";
std::cin >> rhs;
std::cout
<< lhs
<< " "
<< maths.action()
<< " "
<< rhs
<< " = "
<< maths(lhs, rhs)
<< std::endl;
}
int main()
{
bool bQuit = false;
do
{
std::cout
<< std::endl
<< "Choose: -"
<< std::endl
<< " [A]dd"
<< std::endl
<< " [S]ubtract"
<< std::endl
<< " [Q]uit"
<< std::endl
<< std::endl
<< ":> ";
std::string sOpt;
std::cin >> sOpt;
if(!sOpt.empty())
{
switch(sOpt[0])
{
case 'a':
case 'A':
DoMaths(Add());
break;
case 's':
case 'S':
DoMaths(Sub());
break;
case 'q':
case 'Q':
bQuit = true;
break;
}
}
}
while(!bQuit);
return 0;
}
#include <iostream>
#include <string>
struct Add
{
char const * action() const { return "+"; };
int operator()(int lhs_, int rhs_) const
{
return lhs_ + rhs_;
}
};
struct Sub
{
char const * action() const { return "-"; };
int operator()(int lhs_, int rhs_) const
{
return lhs_ - rhs_;
}
};
template <typename mathsT>
void DoMaths()
{
mathsT maths;
int lhs = 0;
int rhs = 0;
std::cout << "Enter first number: ";
std::cin >> lhs;
std::cout << "Enter second number: ";
std::cin >> rhs;
std::cout
<< lhs
<< " "
<< maths.action()
<< " "
<< rhs
<< " = "
<< maths(lhs, rhs)
<< std::endl;
}
int main()
{
bool bQuit = false;
do
{
std::cout
<< std::endl
<< "Choose: -"
<< std::endl
<< " [A]dd"
<< std::endl
<< " [S]ubtract"
<< std::endl
<< " [Q]uit"
<< std::endl
<< std::endl
<< ":> ";
std::string sOpt;
std::cin >> sOpt;
if(!sOpt.empty())
{
switch(sOpt[0])
{
case 'a':
case 'A':
DoMaths<Add>();
break;
case 's':
case 'S':
DoMaths<Sub>();
break;
case 'q':
case 'Q':
bQuit = true;
break;
}
}
}
while(!bQuit);
return 0;
}
Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.
Have a better answer? Share it in a comment.
You could create an Adder class that has a getTerms method that asks the user to input the two values to be added, and that has an add method which adds the two values together and returns the sum. You'll of course have to have two value members, one for each term.
Similar for subtracting.
Once you've created the classes, you can call their methods from the Options class.
Note that I said Options, and not options ... It's common to have an uppercase first letter for class names.