Originally Posted by
alfa_80
Any idea how to fix it. Thanks in advance.
One option available to you is to employ the "boost" C++ library. For example:
Code:
#include <boost/bind.hpp>
#include <string>
#include <sstream>
#include <iostream>
struct X
{
int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
int mul(int a, int b) { return a * b; }
int div(int a, int b) { return a / b; }
int err(int a, int b) { throw int(-1); }
};
int main()
{
// Gather input from the user (note, there is no error checking)
//
std::string input;
char op;
int num1, num2;
std::cout << "Enter first number: ";
std::getline(std::cin, input);
std::istringstream iss(input);
iss >> num1;
std::cout << "Enter an operator (ie. +, -, *, or /): ";
std::getline(std::cin, input);
op = input[0];
std::cout << "Enter second number: ";
std::getline(std::cin, input);
iss.clear();
iss.str(input);
iss >> num2;
// Setup pointer to desired function based on what the user inputted.
//
int (X::*func)(int, int);
switch (op)
{
case '+' : func = &X::add; break;
case '-' : func = &X::sub; break;
case '*' : func = &X::mul; break;
case '/' : func = &X::div; break;
default : func = &X::err; break;
}
// Instantiate an object of type X
//
X x;
// We bind function 'func' to be callable using a reference to
// our object 'x' (thus obviating the need to make the class
// functions static), and this function will accept two parameters,
// those being _1 and _2. We then call the function, passing num1
// and num2, and then save our result.
//
int result = boost::bind(func, boost::ref(x), _1, _2)(num1, num2);
std::cout << result << std::endl;
}
Bookmarks