所以即时尝试为我的程序中的一些自动化实体创建基本状态机系统。如何存储和执行基类中的衍生类成员函数
这个想法是,自动化实体只会调用当前状态或当前分配的行为。每个状态将被分配到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类成员函数的基类。
或者,什么是存储通用成员类函数的方法,并调用它?
在此先感谢。
我认为问题是派生函数正在寻找派生类型成员变量,而基类没有它们。我怀疑C++中的强类型继承系统可能不是理想的方法。如何让一个包含属性的类类型(如'std :: map')和接受Functors(函数对象)来处理属性? –
Galik
2014-09-27 06:18:03