将一个对象的功能传递给另一个对象

时间:2018-11-30 14:19:35

标签: c++ function-pointers

我想将一个对象的功能作为参数传递给另一个功能。下面的代码仅用于指示问题(不是实际的代码)。函数IdNeeded如何可以获取Bar类的函数getNextId?

class Foo
{
public:
   void IdNeeded(getNextId);
}

class Bar
{
public:
   int getNextId()
   {
      return ++id;
   }
private:
   int id = 0;
}

int main()
{
    Bar bar;
    Foo foo;
    foo.IdNeeded(bar.getNextId); // foo will get id = 1

    Foo anotherFoo;
    anotherFoo.IdNeeded(bar.getNextId); // anotherFoo will get id = 2, because "id" is already incremented by one for foo object
}

我尝试使用std :: function,函数指针,std :: bind,但不幸的是无法达成最终解决方案。

1 个答案:

答案 0 :(得分:1)

提供正确的回调定义,并使用lambda打包对象Foo

#include <functional>

class Foo
{
public:
   void IdNeeded(std::function<int()> f){ f();}
};

class Bar
{
public:
   int getNextId()
   {
      return ++id;
   }
private:
   int id = 0;
};

int main()
{
    Bar bar;
    Foo foo;
    foo.IdNeeded([&](){return bar.getNextId();}); // foo will get id = 1
}
相关问题