2013-06-05 78 views
4

我想传递一个函数作为参数与空指针的另一个功能,这是行不通的C++传递函数作为参数另一个函数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; 
} 

事情是无效的函数指针我可能会成为像

#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(); 
} 

一个更简单的代码,但我知道wonna如果我可以使用空指针

它是为实现这样的事情

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; 
} 
+1

它怎么不工作? – mfontanini

+0

'void execute(void * f())'在语法上不正确。 –

+1

我知道,即时通讯要求更正 –

回答

4

使用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 *,你不需要演员。

NOTE:鉴于您传递的是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 
} 

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

+0

我已经更新了我的答案以涵盖void指针。 – reece

+0

所以它不可能呢?我的意思是,传递一个void函数的指针?非常感谢 –

+0

通过“void pointer with functions”传递你的意思是什么?你的意思是传递一个返回指向另一个函数的指针的函数(你可以这样做)? – reece

0

使用

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

或者更好地利用:

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

接受函子为好,或者如果你正在使用的编译器,它支持C++ 11

std::取代 boost::
+0

为什么使用std :: function而不是普通的指针?也许一些(旧)API需要c样式的函数,替换所有的出现并没有一个好的委托实现是不安全的,我认为你不应该 – WorldSEnder

相关问题