gpt4 book ai didi

c++ - 如何在基类中存储和执行派生类成员函数

转载 作者:太空宇宙 更新时间:2023-11-04 13:45:47 24 4
gpt4 key购买 nike

所以我正在尝试为我的程序中的一些自动化实体创建一个基本的状态机系统。

这个想法是,自动化实体将简单地调用当前分配给它的任何当前状态或行为。每个状态将分配给 1 个功能。

我的成员函数指针存在不兼容问题。显然不可能简单地调用“派生成员函数指针”,就好像它是“基本成员函数指针”一样。

我相信我需要能够存储某种“通用类成员函数指针”。我一直在阅读许多其他帖子,他们正在谈论使用 boost::bind 和 boost:function 作为一个选项。虽然我不太确定如何在我的代码上下文中使用它:

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

由于我的自动化实体将具有未知数量的状态,因此具有未知数量的功能,因此我无法创建通用虚拟方法。

存储和执行基类的派生类成员函数的最佳方式是什么。

或者,存储通用成员类函数并调用它的方法是什么?

提前致谢。

最佳答案

是的,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::bind

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

我发现以下链接非常有用。开门见山,在我看来比 boost 文档本身更清楚:

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

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

这些链接还详细介绍了如何使用带有参数和不同返回类型的函数。

关于c++ - 如何在基类中存储和执行派生类成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26071402/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com