C C++中怎么定义一个函数的指针

分别给出在 C 和 C++ 中声明(引出)普通函数指针和成员函数指针的示例。


一、在 C 中声明普通函数指针

#include 

/* 普通函数 */
int add(int a, int b) {
    return a + b;
}

int main(void) {
    /* 1. 直接声明 */
    int (*fp)(int, int) = add;

    /* 2. 使用 typedef 简化 */
    typedef int (*BinOp)(int, int);
    BinOp op = add;

    int r1 = fp(2, 3);   /* 调用 */
    int r2 = op(5, 7);
    printf("%d, %d\n", r1, r2);  /* 输出 5, 12 */
    return 0;
}
  • 语法格式:
    返回类型 (*指针变量名)(参数列表)
  • 调用时直接用 fp(arg1, arg2)

二、在 C++ 中声明普通函数指针

C++ 对普通函数指针的语法和 C 几乎完全相同:

#include 

int add(int a, int b) {
    return a + b;
}

int main() {
    // 1. 直接声明
    int (*fp)(int, int) = add;

    // 2. typedef
    typedef int (*BinOp)(int, int);
    BinOp op = &add;  // 加上 & 也可以

    std::cout << fp(3, 4) << ", "
              << op(8, 9) << "\n";  // 输出 7, 17
    return 0;
}

三、在 C++ 中声明成员函数指针

C++ 独有:可以指向某个类的成员函数。

#include 

class Foo {
public:
    int mul(int x) { return x * factor; }
    Foo(int f): factor(f) {}
private:
    int factor;
};

int main() {
    // 成员函数指针语法:
    // 返回类型 (类名::*指针名)(参数列表)
    int (Foo::*mfptr)(int) = &Foo::mul;

    Foo f1(10), f2(20);

    // 调用方式:
    int r1 = (f1.*mfptr)(3);  // f1.mul(3)
    int r2 = (f2.*mfptr)(4);  // f2.mul(4)

    std::cout << r1 << ", " << r2 << "\n";  // 输出 30, 80
    return 0;
}
  • 声明:返回类型 (ClassName::*ptrName)(参数列表) = &ClassName::MemberFunc;
  • 调用:
    • 在对象上: (obj.*ptrName)(args…)
    • 在指针上: (ptrObj->*ptrName)(args…)

四、C++11 以后更灵活的写法

对于“可存储任何可调用对象”的需求,C++11 引入了 std::function 及 lambda:

#include 
#include 

int add(int a, int b) { return a + b; }

int main() {
    std::function<int(int,int)> f = add;            // 绑定普通函数
    std::function<int(int,int)> g = [](int x,int y){
        return x*y;                                  // 绑定 lambda
    };

    std::cout << f(5,6) << ", " << g(5,6) << "\n";   // 输出 11, 30
    return 0;
}
  • std::function 可以存放
    • 普通函数
    • Lambda 表达式
    • std::bind/std::mem_fn 的结果
    • 以及其他重载了 operator() 的对象

通过以上示例,你可以在 C/C++ 中分别声明并使用普通函数指针、C++ 的成员函数指针,以及 C++11+ 的更通用的 std::function

你可能感兴趣的:(c语言,c++)