Calling a method on a map from another method
-
10-10-2019 - |
Question
// Penguin.h
#include <map>
#include <iostream>
class Penguin
{
typedef void (Penguin::*PenguinMet)();
std::map<int, PenguinMet> Methods;
void Move();
int p;
public:
Penguin();
void Walk();
};
Penguin::Penguin()
{
p = 0;
Methods[0] = &Penguin::Move;
}
void Penguin::Move()
{
std::cout << p << std::endl;
}
void Penguin::Walk()
{
this->*Methods[p];
*this.*Methods[p];
}
and this main()
// Main.cpp
#include "Penguin.h"
int main()
{
Penguin Tux;
Tux.Walk();
return 0;
}
But when I run it p is never printed.
What am I doing wrong?
Thanks
Solution
You're not actually calling the function, you're just looking at the value of the member function pointer as a void expression, which has no effect. Change Penguin::Walk
to this:
void Penguin::Walk()
{
(this->*Methods[p])();
(*this.*Methods[p])();
}
That way you're actually calling the method and passing in the proper arguments (zero arguments, in this case). Note that you need the extra parentheses, since function calls have higher precedence than the ->*
and .*
operators.
OTHER TIPS
That's because you never call the function.
void Penguin::Walk()
{
this->*Methods[p];
*this.*Methods[p];
}
That function does nothing.
void Penguin::Walk()
{
(this->*Methods[p])();
(*this.*Methods[p])();
}
That function calls the thing twice.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow