如何使用参数将函数从一个结构传递到另一个结构中的另一个函数

How to pass a function from 1 struct to another function in a different struct using parameter

本文关键字:结构 另一个 函数 一个 参数 何使用      更新时间:2023-10-16

我正在学习将函数作为参数传递的概念。

首先,我尝试传递"免费函数"?(不属于任何类或结构的函数)到另一个自由函数使用此指针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使这变得更加简单和通用。

考虑这个例子:

#include <iostream>
using namespace std;
struct A {
void Func_A (void (*Func)(int)) {
(*Func)(5);
}
};
struct B {
int x;
void Func_B (int a) {
cout << a << " " << x;
}
};
int main () {
A a;
B b1;
b1.x = 1;
B b2;
b2.x = 2;
a.Func_A(b1.Func_B);
return 0;
}

在该示例中,Func_B同时使用输入 a 和数据成员 x,因此很明显,如果调用 Func_B 的是 b1 或 b2,则调用 的结果会因对象而异。

您可能会认为将函数指针"b1.Func_B"将澄清您指的是与 b1 对象关联的函数,但这不起作用,因为成员函数并非为每个实例单独存在。该函数Func_B内存中仅存在一次,因此不可能为"b1.Func_B"和"B2.Func_B"。所以,它行不通。

g++ 8.2.0 编译器为代码中的a.Func_A(b1.Func_B);行提供以下错误消息:

error: invalid use of non-static member function ‘void B::Func_B(int)’

暗示可以为静态成员函数做这样的事情。这是有道理的,因为静态成员函数不能利用任何实例的数据成员,所以它更像是一个"自由函数",不依赖于任何实例。

相关文章: