我正在尝试将一个函数作为参数传递给另一个带有 void 指针的函数,但它不起作用
#include <iostream>
using namespace std;
void print()
{
cout << "hello!" << endl;
}
void execute(void* f()) //receives the address of print
{
void (*john)(); // declares pointer to function
john = (void*) f; // assigns address of print to pointer, specifying print returns nothing
john(); // execute pointer
}
int main()
{
execute(&print); // function that sends the address of print
return 0;
}
问题是 void 函数指针,我可以编写更简单的代码,例如
#include <iostream>
using namespace std;
void print();
void execute(void());
int main()
{
execute(print); // sends address of print
return 0;
}
void print()
{
cout << "Hello!" << endl;
}
void execute(void f()) // receive address of print
{
f();
}
但我不知道我是否可以使用 void 指针
它是为了实现这样的东西
void print()
{
cout << "hello!" << endl;
}
void increase(int& a)
{
a++;
}
void execute(void *f) //receives the address of print
{
void (*john)(); // declares pointer to function
john = f; // assigns address of print to pointer
john(); // execute pointer
}
int main()
{
int a = 15;
execute(increase(a));
execute(&print); // function that sends the address of print
cout << a << endl;
return 0;
}