2014-09-27 41 views
1

所以即時嘗試爲我的程序中的一些自動化實體創建基本狀態機系統。如何存儲和執行基類中的衍生類成員函數

這個想法是,自動化實體只會調用當前狀態或當前分配的行爲。每個狀態將被分配到1個功能。

Im與我的成員函數指針有不兼容問題。它顯然不可能簡單地調用「派生成員函數指針」,就好像它是「基本成員函數指針」一樣。

我相信我需要能夠存儲某種「通用類成員函數指針」。我一直在閱讀很多其他帖子,他們正在討論使用boost :: bind和boost:函數作爲選項。雖然我不是很清楚如何使用我的代碼範圍內:

#include "stdafx.h" 
#include <iostream> 

using namespace std; 

class Automated 
{ 
public: 

    typedef void (Automated::*behaviourFunc)(); 

    void SetBehaviour(behaviourFunc newBehavFunc) 
    { 
     currentFunction = newBehavFunc; 
    } 

private: 

    behaviourFunc currentFunction; 

protected: 

    void executeCurrentBehaviour() 
    { 
     (this->*currentFunction)(); 
    } 
}; 

class Animal : public Automated 
{ 
public: 

    void update() 
    { 
     executeCurrentBehaviour(); 
    } 
}; 

class Cat : public Animal 
{ 
    int fishCount; 

    void CatchFish() 
    { 
     fishCount++; 
    } 

    void eatFish() 
    { 
     fishCount--; 
    } 
}; 

class Dog : public Animal 
{ 
    int boneCount; 

    void FindBone() 
    { 
     boneCount++; 
    } 

    void throwBone() 
    { 
     boneCount--; 
    } 

public: 

    Dog() 
    { 
     SetBehaviour(FindBone); //Error: argument of type "void (Dog::*)()" is incompatible with parameter of type "Automated::behaviourFunc" 
    } 
}; 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    Dog jake; 
    Cat nemo; 

    nemo.SetBehaviour(Cat::CatchFish); //Error function "Cat::CatchFish" is inaccessible 

    jake.update(); 
    nemo.update(); 

    return 0; 
} 

因爲我的自動化實體將有狀態的未知量,因此具有的功能未知量,我不能創建通用的虛擬方法。

什麼是最好的方式來存儲,並執行一個derrived類成員函數的基類。

或者,什麼是存儲通用成員類函數的方法,並調用它?

在此先感謝。

+0

我認爲問題是派生函數正在尋找派生類型成員變量,而基類沒有它們。我懷疑C++中的強類型繼承系統可能不是理想的方法。如何讓一個包含屬性的類類型(如'std :: map ')和接受Functors(函數對象)來處理屬性? – Galik 2014-09-27 06:18:03

回答

0

所以是的boost :: function和boost :: bind幾乎就是我正在尋找的。

我可以在類「自動化」中存儲boost :: function。

#include <boost/function.hpp> 

class Automated 
{ 
    //ideally there should use a function to set the "currentFunction" but 
    //for learning purposes just make it public 
    public: 

     //function returns void, and no paramters 
     boost::function<void()> currentFunction; 

     //etc 
} 

然後簡單的boost ::綁定在派生類

#include <boost/bind.hpp> 

class Cat : public Animal 
{ 
    int fishCount; 

    void CatchFish() 
    { 
     fishCount++; 
    } 

    void eatFish() 
    { 
     fishCount--; 
    } 

    Cat() 
    { 
     //This bind specifies a void return and no paramters just like the 
     //the signature for the "currentFunction" 
     currentFunction = boost::bind(&HF_BattleEnemyBat::CatchFish, this) 

     //You can simply call "currentFunction" like this: 
     currentFunction(); 
    } 
}; 

我發現下面的鏈接,是非常有益的。開門見山,在我看來有很多比提升文檔自己更清楚:

http://www.radmangames.com/programming/how-to-use-boost-function

http://www.radmangames.com/programming/how-to-use-boost-bind

這些鏈接也去詳細瞭解如何使用功能與參數和不同收益類型。

相關問題