我正在学习将函数作为参数传递的概念。
首先我尝试传递一个“免费函数?” (不属于任何类或结构的函数)使用此指针void(*Func)(int)
到另一个自由函数并且它起作用了。
其次,使用相同指针的自由函数到属于结构的函数也有效。
但是当我尝试将结构中的函数传递给具有相同指针的不同结构中的另一个函数时,它提示错误。
这是我的代码:
#include <iostream>
#include <stdio.h>
#include <windows.h>
#include <conio.h>
using namespace std;
struct A {
void Func_A (void (*Func)(int)) {
(*Func)(5);
}
};
struct B {
void Func_B (int a) {
cout<<a;
}
};
int main () {
A a;
B b;
a.Func_A(b.Func_B);
char key = getch();
return 0;
}
这里错误提示:
[Error] no matching function for call to 'A::Func_A(<unresolved overloaded function type>)'
最佳答案
要传递非静态成员函数,语法略有不同。这是您的原始代码,经过修改以显示这一点:
#include <iostream>
struct B {
void Func_B (int a) {
std::cout << a;
}
};
struct A {
void Func_A (void (B::*Func)(int), B &b) {
(b.*Func) (5);
}
};
int main () {
A a;
B b;
a.Func_A (&B::Func_B, b);
return 0;
}
请注意 Func_A
的不同函数签名,以及调用它时必须传递类 B
的实例。
很遗憾您不能使用 C++11。 std::function
使这变得更加简单和通用。
关于c++ - 如何使用参数将函数从一个结构传递到另一个结构中的另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55705750/