c++将函数作为参数传递给另一个带有void指针的函数

标签 c++ function pointers arguments 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;
}

最佳答案

使用 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]

f 参数的签名不正确。你需要使用

void execute(void (* f)())

相反。因此,在分配给 john 时不需要强制转换:

john = f

此外,您可以通过直接调用 f 来简化此操作:

f(); // execute function pointer

编辑:因为您想使用空指针,所以您需要将 f 作为空指针传递:

void execute(void *f)

在这里,您将需要分配给 john,但由于 f 已经是 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
}

使用专门定义的函数指针可以让编译器在您传递了错误的参数类型时产生错误。这比在运行时崩溃更可取,因为运行时崩溃可能被用作安全漏洞,需要进行大量测试以确保不会发生此错误。

关于c++将函数作为参数传递给另一个带有void指针的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16941903/

相关文章:

c++ - 使用指向成员的指针将成员函数作为参数传递

javascript - 将 const 转换为 JavaScript 中的函数 - React

java - 在不使用 split Java 的情况下从字符串中添加数字

c - char *[] 和 char (*)[] 的区别

c++ - object* foo(bar) 是做什么的?

c++ - 更新 Makefile 以适应当今的标准

c++ - 如何删除树的 child

c++ - Windows 窗体 - 图片框。如何删除图像

c++ - 获取成员变量值设置然后传递给函数c++

pointers - 当对象是指针时重载 == 和 !==