函数指针说明

function pointer explanation

本文关键字:说明 指针 函数      更新时间:2023-10-16

我正在学习C++,只是玩函数指针。

我有这个非常简单的程序,但是调用时没有获得任何输出。你介意解释一下为什么吗?我想这是因为在printTheNumbers内部,我从来没有调用函数本身,我只是引用它?

void sayHello()
{
    cout << "hello there, I was accessed through another functionn";
}
void accessFunctionThroughPointer(int a, int b, void(*function)())
{
}
int main(int argc, const char * argv[])
{
    printTheNumbers(2, 3, sayHello);
    return 0;
}

你的函数没有做任何事情:

void printTheNumbers(int a, int b, void (*function)()){
    // there is no body here    
}

您需要实际调用传入的函数指针:

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

你传入sayHello函数来打印TheNumbers,但你从不调用传递的函数。

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

代码片段

更考虑使用std::function。例:

#include <functional>
void printTheNumbers(int a, int b, std::function<void()> function){ 
    function();
}

在大多数情况下,std::函数就足够了,而且更具可读性。