如何在两个类之间使用功能指针

How to use function pointer between 2 classes

本文关键字:之间 指针 功能 两个      更新时间:2023-10-16

我有两个类别说" A级"answers" B类"。我试图在" A类"中声明函数指针原型,并在" B类"中使用它,但失败了。请查看我的示例代码,并帮助我如何成功。

#include "stdafx.h"
#include <iostream>   
using namespace std;
class A
{
  public:
    int (*funcPtr)(int,int);
    void PointerTesting(int (*funcPtr)(int,int))
    {               
       //i need to get B::test as an function pointer argument
    }
 };
 class B
 {
    public:
      int test(int a,int b)
      {
        return a+b;
      }
  };
  int _tmain(int argc, _TCHAR* argv[])
  { 
    int (A::*fptr) (char*) = &B::test;  
    getchar();
    return 0; 
  }

建议:use&lt;功能>,std ::功能和std :: bind

#include <iostream>   
#include <functional>
using namespace std;
class A {
public:
    using FnPtr = std::function<int(int, int)>;
    void PointerTesting(const FnPtr& fn) {               
        //i need to get B::test as an function pointer argument
        // Example: Print 1 and 2's sum.
        int result = fn(1, 2);
        std::cout << "Result: " << result << std::endl;
    }
};
class B {
public:
    int test(int a,int b) {
        return (a+b);
    }
};
int main(int argc, char* argv[]) { 
    A a;
    B b;
    A::FnPtr ptr = std::bind(&B::test, b, std::placeholders::_1, std::placeholders::_2);
    a.PointerTesting(ptr);
    getchar();
    return 0; 
}

http://en.cppreference.com/w/cpp/utility/functional/bindhttp://en.cppreference.com/w/cpp/utility/functional/function