4

我正在尝试将一个函数作为参数传递给另一个带有 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;
}
4

2 回答 2

5

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

编辑:由于您想使用 void 指针,因此需要f作为 void 指针传递:

void execute(void *f)

在这里,您将需要分配 to john,但因为f已经是 avoid *您不需要演员表。

注意:鉴于您传递的是一个 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
}

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

于 2013-06-05T14:05:52.313 回答
0

利用

void execute(void (*f)()) //receives the address of print

或者更好地使用:

void execute(boost::function<void()> const & f) //receives the address of print

也接受函子,或者如果您使用的是支持 C++11 的编译器,则替换boost::std::

于 2013-06-05T14:09:46.800 回答