Last active
August 29, 2015 13:56
-
-
Save bahostetterlewis/9220942 to your computer and use it in GitHub Desktop.
Creating a map of member functions example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <map> | |
using namespace std; | |
class node{ | |
public: | |
node(int val){this->val = val; } | |
int val; | |
}; | |
class funcs{ | |
public: | |
funcs(char, node*, node*); | |
int eval(); | |
int sub(); | |
int add(); | |
node* left; | |
node* right; | |
int val; | |
char op; | |
map<char, int (funcs::*)()> mapper; | |
}; | |
funcs::funcs(char op, node* left, node* right){ | |
this->op = op; | |
this->left = left; | |
this->right = right; | |
this->mapper['+'] = &funcs::add; | |
this->mapper['-'] = &funcs::sub; | |
} | |
int funcs::eval(){ | |
return (this->*mapper[this->op])(); | |
} | |
int funcs::add(){ | |
return this->left->val + this->right->val; | |
} | |
int funcs::sub(){ | |
return this->left->val - this->right->val; | |
} | |
int main(){ | |
node *a = new node(10); | |
node *b = new node(20); | |
funcs f('+', a, b); | |
cout << f.eval() << endl; | |
funcs f2('-', a, b); | |
cout << f2.eval() << endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment