Skip to content

Instantly share code, notes, and snippets.

@hucancode
Created August 25, 2022 00:23
Show Gist options
  • Save hucancode/b4d89e4f7093d01a20f3d76c0c7d30c4 to your computer and use it in GitHub Desktop.
Save hucancode/b4d89e4f7093d01a20f3d76c0c7d30c4 to your computer and use it in GitHub Desktop.
c++ function pointer demo
#include <iostream>
using namespace std;
class AttackFunctionObject
{
public:
virtual void operator()(int damage)
{
printf("attack\n");
}
};
class BossAttack : public AttackFunctionObject
{
public:
virtual void operator()(int damage)
{
printf("boss attack with %d damages\n", damage);
}
};
class MobAttack : public AttackFunctionObject
{
public:
virtual void operator()(int damage)
{
printf("mob attack with %d damages\n", damage);
}
};
int main()
{
AttackFunctionObject* attack_function;
{// if this and that and what ever
attack_function = new MobAttack();
(*attack_function)(10);
delete attack_function;
}
{// if this and that and what ever
attack_function = new BossAttack();
(*attack_function)(10);
delete attack_function;
}
system("pause");
return 0;
}
#include <iostream>
class Mob
{
public:
int damage;
Mob()
{
damage = 99;
}
void Attack(int target)
{
printf("Mob::Attack inflict %d damages to %d\n", damage, target);
}
static void Fly(int height)
{
printf("Mob::Fly fly up to %d m height\n", height);
}
};
void Mob__Attack(int damage, int target)
{
printf("Mob__Attack inflict %d damages to %d\n", damage, target);
}
#define DECLARE_STATIC_FUNCTION(name, ...) typedef void (*name) (__VA_ARGS__)
#define DECLARE_MEMBER_FUNCTION(class, name, ...) typedef void (class::*name) (__VA_ARGS__)
int main()
{
Mob* mob = new Mob();
{
typedef void (*Attack_Static) (int, int);
Attack_Static attack_function = &Mob__Attack;
(*attack_function)(12, 4);
}
{
DECLARE_STATIC_FUNCTION(Attack_Static, int, int);
Attack_Static attack_function = &Mob__Attack;
(*attack_function)(12, 4);
}
{
typedef void (Mob::*Attack_ClassMember)(int);
Attack_ClassMember attack_function = &Mob::Attack;
(mob->*attack_function)(4);
}
{
DECLARE_MEMBER_FUNCTION(Mob, Attack_ClassMember, int);
Attack_ClassMember attack_function = &Mob::Attack;
(mob->*attack_function)(4);
}
{
typedef void(*FLy_StaticMember)(int);
FLy_StaticMember fly_function = &Mob::Fly;
(*fly_function)(20);
}
{
DECLARE_STATIC_FUNCTION(FLy_StaticMember, int);
FLy_StaticMember fly_function = &Mob::Fly;
(*fly_function)(20);
}
system("pause");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment