如何在2个类

时间:2017-05-29 09:06:42

标签: c++

  

我有2个班级说“A级”和“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; 
  }

1 个答案:

答案 0 :(得分:2)

建议:使用&lt;功能&gt;,std :: function和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/bind http://en.cppreference.com/w/cpp/utility/functional/function