首页 > 解决方案 > 在 C++ 中声明函数指针的 typedef

问题描述

我知道以前有人问过类似的问题和答案。我已经理解了函数指针的概念及其声明的含义。以下是我的函数指针示例代码,其中我将函数指针分配为指向fp_GetBiggerElement函数GetBiggerElement

    #include <iostream>

    typedef     int     (*fp_GetBiggerElement)      (int, int);
    //           ^                ^                     ^
    //      return type      type name              arguments

    using namespace std;

    int GetBiggerElement(int arg1, int arg2)
    {
        int bigger = arg1 > arg2 ? arg1 : arg2;
        return bigger;
    }

    int main()
    {
        fp_GetBiggerElement funcPtr = GetBiggerElement;

        int valueReturned = funcPtr(10, 20);
        cout << valueReturned << endl;
        return 0;
    }

我的理解是,typedef意味着为一个类型定义一个新的定义。通常,typedef语句需要two-parts(或说两个参数)

  1. 第一部分是需要新别名的类型

  2. 第二部分是一个新的别名

    typedef     unsigned  int       UnsignedInt;
    //              ^                   ^                       
    //          (original type)     (Alias)
    

例如,在上面的代码中,第一部分是unsigned int,第二部分是UnsignedInt

    typedef     char *              CharPtr;
    //              ^                   ^                       
    //      (original type)          (Alias)

同样,在上面的第二个例子中,第一部分是char*,第二部分是CharPtr

问题:typedef我对函数指针语句的格式感到困惑。在语句typedef int(*fp_GetBiggerElement)(int, int);中,没有遵循典型的两个参数格式,typedef那么它是如何工作的?

更新:我知道 C++11 提供了另一种声明函数指针的方式,即(通过using声明)。在这个问题中,我只想了解typedef函数指针的语句语法。

标签: c++typedef

解决方案


我认为考虑typedef语法的最佳想法就像声明要 typedef 的类型的变量。例如:

char *CharPtr;// declare CharPtr to be variable of type char*

typedef char *CharPtr_t;// declare CharPtr_t to be alias of type char*

与函数指针类似:

int (*fp) (int, int);// declare fp as pointer to int(int, int)

typedef int (*fp_t)(int, int);// declare fp_t to be alias of pointer to int(int, int)

顺便说一句,在 C++11 中,您将获得不那么令人困惑(并且更强大)的替代方案typedef- using。您应该改用(双关语)它。只是看看:

using fp = int (*)(int, int);// declare fp_t to be alias of pointer to int(int, int)

推荐阅读