cocos2dx3.2 C++再談談函數指針的簡單使用

一般情況:

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)


接下來再定義一個類Player,繼承Node:

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;

    

}



然後再main函數這樣使用:

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是再裏面調用的,其實使用也是蠻簡單的,看下:

比如我要再Player::init函數中調用:

bool Player::init()

{

    SEL_SCHEDULE sel = schedule_selector(Player::show);

    (this->*sel)(3.0f);

    return true;

    

}

好了到此結束吧.













發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章