C++函数指针 学习笔记

无参函数指针的声明和调用

#include <iostream>
int func1()
{
    return 1;
}
int main()
{
    int (*ptrFunc)();
    ptrFunc = func1;
    std::cout<<(*ptrFunc)();
    return 0;
}

运行以上代码,控制台输出1。



第8行 函数指针的声明。int对应函数返回类型。

第9行 指针的赋值。

第10行 函数指针的调用。不要漏了后面的一对括号。


带参数的函数指针的声明和调用

#include <iostream>
int add(int a, int b)
{
    return a + b;
}
int main()
{
    int (*ptrFunc)(int, int);
    ptrFunc = add;
    std::cout<<(*ptrFunc)(1,2);
    return 0;
}


运行以上代码,控制台输出3。

第8行 相比上一段代码,同样是函数指针的声明,第2个括号中多了2个int,这对应函数的参数。


别名typedef

函数指针的声明比较复杂,通常为它起个别名。

typedef int(*LPFUNCADD) (int,int);  //返回类型(*别名) (参数1, 参数2)


函数指针的定义可以简写成这样。

LPFUNCADD ptrFunc;


完整代码如下

#include <iostream>
int add(int a, int b)
{
    return a + b;
}
typedef int(*LPFUNCADD) (int,int);  //返回类型(*别名) (参数1, 参数2)
int main()
{
    LPFUNCADD ptrFunc;
    ptrFunc = add;
    std::cout<<(*ptrFunc)(1,2);
    return 0;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章