如何使用参数将函数从一个结构传递到另一个结构中的另一个函数
How to pass a function from 1 struct to another function in a different struct using parameter
我正在学习将函数作为参数传递的概念。
首先,我尝试传递"免费函数"?(不属于任何类或结构的函数)到另一个自由函数使用此指针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)’
暗示可以为静态成员函数做这样的事情。这是有道理的,因为静态成员函数不能利用任何实例的数据成员,所以它更像是一个"自由函数",不依赖于任何实例。
相关文章:
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么将一个结构的引用设置为等于另一个结构只会更改一个数据成员?
- 从另一个 cpp 文件更改结构内、映射键内的变量
- 如何将一个结构的字符数组复制到结构的另一个字符数组中?
- 如何将数据从一个结构链接到另一个结构
- 是否可以使用智能指针成员设置具有另一个结构的结构?
- std::transform 将一个结构数组复制到另一个结构数组
- C++将结构复制到另一个程序的资源
- 结构新手,我对如何从 void 函数中返回值并将其放入另一个函数感到困惑
- 可以访问一个类中的播放器结构,但不能访问另一个类中的播放器结构
- 如何在另一个结构中初始化结构数组?
- 在另一个结构中声明内部结构会导致错误:结构使用无效
- 通过 C++ 中的另一个结构成员访问结构
- 难以从另一个结构中的函数返回结构
- 有没有办法将一个对象注入到另一个对象的结构中?
- 如何制作一个结构程序,在其中可以存储无限量的数据,以便每次您想要时都可以将另一个产品添加到列表中?
- 将一个结构的值复制到另一个结构
- 结构C++可以用 0 初始化,但不能用另一个 int 初始化
- 如何将矢量结构从一个标头文件传递到另一个标头文件中的类
- 是否可以定义一个在外部"C"块中继承另一个结构的结构?