2014-09-27 45 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

这些链接也去详细了解如何使用功能与参数和不同收益类型。

相关问题