C++笔记-函数指针

函数指针语法:

// fcnPtr is a pointer to a function that takes no arguments and returns an integer
int (*fcnPtr)();

特点:

  • 函数指针的类型(参数返回值)都必须和函数的相同。
  • 如果需要c++会隐性的把函数转换成函数指针,不需要用&符号来获得地址
  • 同时c++还会隐性质的把指针dereference
int foo(int x)
{
    return x;
}
int main()
{
    int (*fcnPtr)(int){ &foo }; // Initialize fcnPtr with function foo
    (*fcnPtr)(5); // call function foo(5) through fcnPtr.
    fcnPtr(5); // call function foo(5) through fcnPtr.
    return 0;
}
  • 可以指向nullptr
  • 主要用于callback函数
posted @ 2023-03-07 16:53  一个AI的修养  阅读(19)  评论(0)    收藏  举报