一般情况:
void showMsg(float)
{
cout << "show msg normal" << endl;
}
void (*p)(float);
然后这样调用:
p = showMsg;
p(1.1f);
如果用于函数传递参数,这样就不是很方便使用了,于是有了下面这种:
typedef void (*p1)(float);
p1 p1my = showMsg;
p1my(1.0f);
上面是一般的情况,那么如何指向类成员的成员函数呢?
看下:
class Student
{
public:
void showMsg(float);
};
void Student::showMsg(float)
{
cout << "show msg in the Student Class" << endl;
}
typedef void (Student::*ps)(float);
使用如下:
Student s;
ps pstudent = &Student::showMsg;
(s.*pstudent)(2.0f);
好了,我们已经知道了,函数指针的简单使用,那么我大概模仿下cocos2dx3.2里面的SEL_SCHEDULE的使用:
首先,定义Node节点,这个我随便写的
class Node
{
public:
static Node* create();
void autorelease();
protected:
Node();
virtual bool init();
virtual ~Node();
};
void Node::autorelease()
{
delete this;
}
Node* Node::create()
{
auto sp = new Node();
if(sp && sp->init())
{
}
else
{
delete sp;
}
return sp;
}
Node::Node()
{
}
Node::~Node()
{
cout << "the Node is destructed" << endl;
}
bool Node::init()
{
return true;
}
typedef void (Node::*SEL_SCHEDULE)(float);
#define schedule_selector(_SELECTOR) static_cast<SEL_SCHEDULE>(&_SELECTOR)
class Player : public Node
{
public:
static Player* create();
void show(float dt);
protected:
Player();
virtual ~Player();
virtual bool init();
};
void Player::show(float dt)
{
cout << "player show class" << endl;
}
Player::Player()
{
}
Player::~Player()
{
cout << "the player is destructed" << endl;
}
Player* Player::create()
{
auto sp = new Player();
if(sp && sp->init())
{
}
else
{
delete sp;
}
return sp;
}
bool Player::init()
{
SEL_SCHEDULE sel = schedule_selector(Player::show);
(this->*sel)(3.0f);
return true;
}
int main()
{
auto sp = Player::create();
SEL_SCHEDULE sel = schedule_selector(Player::show);
// SEL_SCHEDULE sel = static_cast<SEL_SCHEDULE>(&Player::show); //这种方式也是可以的
(sp->*sel)(2.2);
sp->autorelease();
return 0;
}
哎,上面这种是再外面使用,但是cocos2dx3.2是再里面调用的,其实使用也是蛮简单的,看下:
boolPlayer::init()
{
SEL_SCHEDULEsel =schedule_selector(Player::show);
(this->*sel)(3.0f);
returntrue;
}
好了到此结束吧.