简体   繁体   English

在C ++中将函数作为参数传递

[英]Passing a function as an argument in c++

I have the following call: 我有以下电话:

void Derived::GetEntry(Skill&);
InorderTraverse(GetEntry);

Which calls 哪个电话

void Base<ItemType>::InorderTraverse(void Visit(ItemType&)) const

Attempting to compile as written generates 尝试以书面形式编译

error C3867: 'Derived::GetEntry': function call missing argument list; 错误C3867:'Derived :: GetEntry':函数调用缺少参数列表; use '&Derived::GetEntry' to create a pointer to member 使用'&Derived :: GetEntry'创建一个指向成员的指针

Using &Derived::GetEntry generates 使用&Derived :: GetEntry生成

cannot convert parameter 1 from 'void (__thiscall Derived::* )(Skill &)' to 'void (__cdecl *)(ItemType &)' 无法将参数1从'void(__thiscall Derived :: *)(Skill&)'转换为'void(__cdecl *)(ItemType&)'

Changing the declaration to static void GetEntry... fixes these problems, but creates a new set of problems (namely that I can't access non-static objects (nonstatic member reference must be relative to a specific object) 将声明更改为静态void GetEntry ...可解决这些问题,但会产生一系列新问题(即我无法访问非静态对象(非静态成员引用必须相对于特定对象)

I have a similar traversal operation that works fine with a static declaration, since the called function just displays information about each object on which it is called. 我有一个类似的遍历操作,可以很好地与静态声明一起使用,因为被调用函数仅显示有关被调用的每个对象的信息。

I've been searching for a few days now for an answer, and I feel like it's something simple. 我一直在寻找答案的几天,我觉得这很简单。 Is there a way to use a nonstatic function as a parameter in another function call? 有没有办法在另一个函数调用中使用非静态函数作为参数?

The complete code is: https://github.com/mindaika/SkillTree 完整的代码是: https : //github.com/mindaika/SkillTree

Edit: Inserted full working example instead. 编辑:插入完整的工作示例。

I suggest you use the std function pointers instead. 我建议您改用std函数指针。

For instance: 例如:

#include <functional>
void main()
{
class TheClass
{
public:

   TheClass()
   {
       m_function = ( std::tr1::bind(&TheClass::run, this) );
   };

   void run()
   {
          // stuff to do
   };

   std::tr1::function<void ()> m_function;
};

TheClass theclass;
theclass.m_function();

}

m_function (); m_function(); // call function //调用函数

As I mentioned in my question, I was trying to get around the "memory leak" caused by using a static variable (it's not actually a leak, since statics are destroyed, but not until after the leak detector runs). 正如我在问题中提到的那样,我试图解决由于使用静态变量而引起的“内存泄漏”(实际上不是泄漏,因为静电被破坏了,但直到泄漏检测器运行之后)。 I ended up using a modification of the encapsulated pointer described here: C++ freeing static variables 我最终使用了对此处描述的封装指针的修改: C ++释放静态变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM