How to send a message to the class that created the object

白昼怎懂夜的黑 提交于 2019-12-11 19:05:15

问题


I would like to send back data to class that create this object.

It's game related. The enemy objects have a threaded function and move on their own in the scene.

It generates lots of errors if you include the header file from the class that creates to the objects into the object itself ... to pass pointers.

Enemy Class:

Class Enemy
{
   private:
      void (*iChange)(DWORD &);
}:
Enemy::Enemy(void (*iChangeHandler)(DWORD &) ) : iChange(0)
{
    this->iChange = iChangeHandler;
}
    void Enemy::Draw(D3DGraphics& gfx)
{
    this->iChange(this->dwThreadID); // send a message back to the class that created me

    gfx.PutPixel(this->my_position_x + 0,this->my_position_y,this->red,this->blue,this->green);
    this->grafix->DrawCircle(this->my_position_x + 0,this->my_position_y, this->radius, this->red,this->blue,this->green);

    (sprintf)( this->enemy_buffer, "X: %d, Y: %d", this->my_position_x , this->my_position_y);
    this->grafix->DrawString( this->enemy_buffer, this->my_position_x , this->my_position_y, &fixedSys, D3DCOLOR_XRGB(255, 0, 0) );
}

Game Class:

struct enemies_array_ARRAY {
        std::string name;
        DWORD ID;
        Enemy* enemy;
    } enemies_array[25];

void Game::EnemyEvent(DWORD &thread_id)
{   
     enemies_array[0]...... // i want to acces this struct array
}

Game::Game(HWND hWnd)
{
    enemies_array[0].name = "john Doe";
    enemies_array[0].ID = NULL;
    enemies_array[0].enemy =  new Enemy(&Game::EnemyEvent);   
    // error: C2664:

    // another attemp
    enemies_array[0].name = "john Doe";
    enemies_array[0].ID = NULL;
    enemies_array[0].enemy =  new Enemy(Game::EnemyEvent);
    // error C3867: 
}

回答1:


If I understand correctly, you want to call a function on the Game object. This means you need to pass a pointer to the Game object in order to correctly call a non static member function pointer(iChange) on it.

Make the changes shown below and you should be able to do what you want

enemies_array[0].enemy =  new Enemy(this,&Game::EnemyEvent);   

typedef void (Game::*ChangeFunc)(DWORD &)
Class Enemy
{
private:
   ChangeFunc iChange;
   Game *pGame;
}:

Enemy(Game *pCreatorGame, ChangeFunc iChangeHandler )
{
    iChange = iChangeHandler;
    pGame = pCreatorGame;
}

void Enemy::Draw(D3DGraphics& gfx)
{
    (pGame->*iChange)(this->dwThreadID);


来源:https://stackoverflow.com/questions/13787181/how-to-send-a-message-to-the-class-that-created-the-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!