如何在两个类之间使用功能指针
How to use function pointer between 2 classes
我有两个类别说" 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
相关文章:
- 在 const 函数中通过引用和指针返回之间的区别
- 共享指针和具有自定义删除程序的唯一指针之间的语法差异背后的任何原因
- 空指针常量 (nullptr)、空指针值和空成员指针值之间有什么区别?
- AVX 指令中寄存器和指针之间的客观差异
- 禁止指针和整数之间的比较C++
- 为什么不同类型层次结构的指针之间的dynamic_cast定义得很好?
- 介于 [固定数组] 和 [带内存分配的指针] 之间的性能
- ISO C++禁止指针和整数 [-fpermissive] [c++] 之间的比较
- 类指针之间的 Qt 差异
- 如何使用静态多态性在 int 和指针类型之间进行转换?
- 指向 POD 类型的指针之间的静态转换与重新解释转换
- 在两个.cpp文件之间定义全局类/结构指针
- 按值和引用传递指针之间的区别?
- 在硬件SIMD矢量指针和相应类型之间进行"interpret_cast"是一种未定义的行为吗
- 在C++中的程序之间共享指针
- 指针和程序性能之间有什么关系吗?
- Qt 错误 iso c++ 禁止指针和整数之间的比较 -permissive
- 可以在指向不同模板类实例的指针之间进行强制转换吗
- C++17:unique_ptr<char[]> 和 shared_ptr<char[] 之间的指针存储差异>
- 错误:ISO C++禁止在指针和整数 [-fallowive] 之间进行比较