【问题标题】:How to send a message to the class that created the object如何向创建对象的类发送消息
【发布时间】:2012-12-09 11:58:14
【问题描述】:

我想将数据发送回创建此对象的类。

这和游戏有关。 敌方物体具有线程功能,并在场景中自行移动。

如果您将创建对象的类中的头文件包含到对象本身中...以传递指针,则会产生很多错误。

敌人等级:

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) );
}

游戏类:

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: 
}

【问题讨论】:

  • 一个类只是一个类型。你不能向一个类型发送任何东西。您可以向 int 发送消息吗?
  • 我正在努力实现你可以用 c# 做的事情......回调我已经阅读了很多关于它的内容......但我没有真正将其解释为与 c# 类似
  • 如果EnemyEvent(DWORD &thread_id) 是静态的......代码可以工作,但我无法访问游戏类中/从游戏类中的变量

标签: c++ winapi events event-handling callback


【解决方案1】:

如果我理解正确,您想在 Game 对象上调用一个函数。这意味着您需要传递一个指向Game 对象的指针,以便在其上正确调用non static member function pointer(iChange)。

进行如下所示的更改,你应该能够做你想做的事

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);

【讨论】:

  • 但我不能 #include "Game.h" 进入 Enemy 类......否则这些确实是可能的......我认为
  • 您只需要在标题中指向游戏的指针 - 只需在 class Enemy{ 上方使用前向声明 class Game
  • 同样,Game.h 不需要在顶部包含 Enemy.h 只需 class Enemy 即可,因为您只需要一个指向敌人的指针。
  • hmmm ... 1>c:\..\game.cpp(78): error C2664: 'Enemy::Enemy(const MouseServer &,int &,int &,Game ,void (__cdecl &)(DWORD &))' : 无法将参数 5 从 'void (__thiscall Game:: )(DWORD &)' 转换为 'void (__cdecl &)(DWORD &)' ` 我做了你告诉我的
  • 我忘记更改函数指针的类型以表明它是成员函数,修复它。我还把函数签名变成了typedef,现在更容易读/写代码。
猜你喜欢
  • 1970-01-01
  • 2011-09-14
  • 1970-01-01
  • 2013-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-07
  • 1970-01-01
相关资源
最近更新 更多