Assigning one function to another?
Hi, I''m starting an RPG battle system. When an action is chosen during combat, the appropriate move function is performed after "switch-caseing" the index of the action selected.
Ex.
switch(index) {
case ATTACK:
DoAttack();
break;
case DEFEND:
Defend();
break;
}
However, with this system I have to re-determin the selection every frame.
I thought up a possible solution, but I''m not sure how to execute it.
My character class has a function called Action(). Can I assign this function to another particular function? That is, make the character''s Action() function point to the appropriate function (such as Attack() or Defend()) and just call character.Action() each frame instead of re-determining the chosen move every frame?
Are you doing this using OOP? If so, you can use something called virtual functions to do exactly what you are looking for. If you are just using straight C code, you can create a function pointer called Action, but you still will have to have a switch statement to update the function pointer (so that will not do what you are looking for).
use a pointer to a function
such as
viod (*pfunc)();
that would point to a function that returns void and takes no paramiters just add paramiters inside the () at the end the way you would the funtion you want it to point to
change void to the return type you want
all possible funtions attack() defened() should accept same number of paramiters and return same type
such as
viod (*pfunc)();
that would point to a function that returns void and takes no paramiters just add paramiters inside the () at the end the way you would the funtion you want it to point to
change void to the return type you want
all possible funtions attack() defened() should accept same number of paramiters and return same type
typedef void func(void);void Attack1() { /*...*/ };void Attack2() { /*...*/ };void Attack3() { /*...*/ };func* AttackTable[3] = { Attack1, Attack2, Attack3 };...func* MyAttack = AttackTable[2];...MyAttack();
Before you ask, this does not easily map to (non-static) class member functions, because pointers to (non-static) member functions are not pointers (they are ''pointer-to-member''s).
Go to function-pointer.org for more details.
Go to Boost for an object-oriented solution.
Documents [ GDNet | MSDN | STL | OpenGL | Formats | RTFM | Asking Smart Questions ]
C++ Stuff [ MinGW | Loki | SDL | Boost. | STLport | FLTK | ACCU Recommended Books ]
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement