I am trying to build an efficient Rock, Paper, Scissors simulator between 2 computer "players." A suggestion I saw here was to use a matrix to store the possible outcomes. I really liked this idea as it means I wouldn't have to have 9 different if() statements to account for all possible values. Whenever a match is completed I have functions to iterate the number of Wins, Losses, and Draws of each player. Thus, I thought it would be great if I could build a 2-dimensional array of function pointers so that [0][0] represents a throw of "Rock" by both parties and would result in a Draw, throwing the function addDraw() for each player. I found an example of a 1-dimensional array of function pointers which works here.
My code is throwing several errors when I try to compile. Let me know if anything else is needed.
Function to call the result:
void Player::result(vector<Player*> &vals, int x, int y)
{
Player *p1 = vals[0];
Player *p2 = vals[1];
void(*results1[3][3]) =
{
{ p1->addDraws, p1->addWins, p1->addLosses },
{ p1->addLosses, p1->addDraws, p1->addWins },
{ p1->addWins, p1->addLosses, p1->addDraws }
};
}
Functions to add Wins, Losses, and Draws:
void Player::addWins()
{
wins++;
}
void Player::addLosses()
{
losses++;
}
void Player::addDraws()
{
draws++;
}
All functions are initialized in Player.h and declared in Player.cpp (I think that's the right terms). The most common error I am receiving is "error C2440: 'initializing' : cannot convert from 'void (__thiscall Player::* )(void)' to 'void *'
You have an array of void pointers, not function pointers, and member functions are not function pointers.
You'll need something like
typedef void (Player::*Score)(); // typedefs and function types go together well
Score scores[3][3]) =
{
{ &Player::addDraws, &Player::addWins, &Player::addLosses },
{ &Player::addLosses, &Player::addDraws, &Player::addWins },
{ &Player::addWins, &Player::addLosses, &Player::addDraws }
};
// Calling
Player a;
(a.*scores[0][0])();
or, use free functions like this:
void addWins(Player* p)
{
p->addWins();
}
// Similar for the others...
typedef void (*Score)();
Score scores[3][3] = {{ addWins, ....
//
Player* player = ...
scores[0][0].addWins(player);
or, you can be modern and use std::function
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With