Ric*_*rio 4 c++ pointers arguments function void
我正在尝试将函数作为参数传递给另一个带有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;
}
Run Code Online (Sandbox Code Playgroud)
事情是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();
}
Run Code Online (Sandbox Code Playgroud)
但我想知道我是否可以使用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;
}
Run Code Online (Sandbox Code Playgroud)
用gcc test.cpp
我得到:
test.cpp: In function ‘void execute(void* (*)())’:
test.cpp:12:22: error: invalid conversion from ‘void*’ to ‘void (*)()’ [-fpermissive]
test.cpp: In function ‘int main()’:
test.cpp:18:19: error: invalid conversion from ‘void (*)()’ to ‘void* (*)()’ [-fpermissive]
test.cpp:9:6: error: initializing argument 1 of ‘void execute(void* (*)())’ [-fpermissive]
Run Code Online (Sandbox Code Playgroud)
f
参数的签名不正确.你需要使用
void execute(void (* f)())
Run Code Online (Sandbox Code Playgroud)
代替.因此,在分配给时,您不需要演员john
:
john = f
Run Code Online (Sandbox Code Playgroud)
此外,您可以通过f
直接调用来简化:
f(); // execute function pointer
Run Code Online (Sandbox Code Playgroud)
编辑:因为你想使用void指针,你需要f
作为一个void指针传递:
void execute(void *f)
Run Code Online (Sandbox Code Playgroud)
在这里,您将需要分配john
,但是f
已经是void *
您不需要演员.
注意:假设您正在传递一个void指针,该execute
函数将接受任何内容,如果您传递错误的东西,您将遇到运行时错误.例如:
void print_name(const char *name)
{
printf("%s", name);
}
void execute1(void *f);
void execute2(void (*f)());
int main()
{
int value = 2;
execute1(&value); // runtime crash
execute1(&print_name); // runtime crash
execute2(&value); // compile-time error
execute2(&print_name); // compile-time error
}
Run Code Online (Sandbox Code Playgroud)
使用特定定义的函数指针,编译器会在您传递错误参数类型的位置生成错误.这在运行时崩溃是首选,因为运行时崩溃可能被利用为安全漏洞,需要进行大量测试以确保不会发生此错误.