Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.
#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;
}
If you are experiencing a similar issue, please ask a related question
Title | # Comments | Views | Activity |
---|---|---|---|
C++ get user from AD (VS6) | 7 | 72 | |
Focus not getting shifted out of editbox | 2 | 62 | |
please insert disk adobe master collection6 | 9 | 874 | |
Precision Problem in C++ | 7 | 31 |
Join the community of 500,000 technology professionals and ask your questions.