函数指针说明 我学习C++,只是玩函数指针。

函数指针说明 我学习C++,只是玩函数指针。,c++,function,pointers,C++,Function,Pointers,我有一个非常简单的程序,但调用时没有任何输出。你能解释一下原因吗?我想这是因为在打印数字中,我从未调用过函数本身,我只是引用了它 void sayHello() { cout << "hello there, I was accessed through another function\n"; } void accessFunctionThroughPointer(int a, int b, void(*function)()) { } int main(int ar

我有一个非常简单的程序,但调用时没有任何输出。你能解释一下原因吗?我想这是因为在
打印数字
中,我从未调用过函数本身,我只是引用了它

void sayHello()
{
    cout << "hello there, I was accessed through another function\n";
}

void accessFunctionThroughPointer(int a, int b, void(*function)())
{

}

int main(int argc, const char * argv[])
{
    printTheNumbers(2, 3, sayHello);

    return 0;
}
void sayHello()
{

不能传入sayHello函数以打印数字,但从未调用传入函数。

传入sayHello函数以打印数字,但从未调用传入函数。

您的函数没有执行任何操作:

void printTheNumbers(int a, int b, void (*function)()){
    // there is no body here    
}
您需要实际调用传入的函数指针:

void printTheNumbers(int a, int b, void (*function)()){
    function();
}

您的函数没有执行任何操作:

void printTheNumbers(int a, int b, void (*function)()){
    // there is no body here    
}
您需要实际调用传入的函数指针:

void printTheNumbers(int a, int b, void (*function)()){
    function();
}

您需要手动调用该函数。请证明:

<> >考虑使用<代码> STD::函数< /代码>。例:

#include <functional>

void printTheNumbers(int a, int b, std::function<void()> function){ 
    function();
}
#包括
无效打印编号(int a、int b、std::function){
函数();
}

在大多数情况下,std::function就足够了,可读性更强。

您需要手动调用该函数。请验证:

<> >考虑使用<代码> STD::函数< /代码>。例:

#include <functional>

void printTheNumbers(int a, int b, std::function<void()> function){ 
    function();
}
#包括
无效打印编号(int a、int b、std::function){
函数();
}

大多数情况下,函数是足够的和可读的。< /P>将此行添加到<代码> PrtTununbsSe()/<代码>:<代码>函数():< /代码>没有冒犯,但正如你所说的,你仍然在学习C++(以及发布与解决方案无关的初学者代码——AddiNuMbS),这将更好地学习与你所知道的一起玩。(函数等)并学习处理字符串、读取命令行、解析参数等。IMHO函数指针很好,但更复杂,不经常需要…编辑。我需要学习最后一个not函数。谢谢我猜?@relascope将这一行添加到

printTheNumbers()
function()但是,正如你所说的,你仍然在学习C++(以及发布与解决方案无关的初学者代码),这将更好地用于学习你所知道的(函数等)。并学习处理字符串、读取命令行、解析参数等。IMHO函数指针很好,但更复杂,而且不经常需要…编辑。我需要学习最后一个not函数。谢谢我猜?@relascope如果我让sayHello()返回字符串而不是void,怎么样返回字符串而不是void。