我了解以前曾问过类似的问题和答案。我已经了解了函数指针的概念及其声明的含义。以下是我的函数指针的示例代码,在这里我分配了函数指针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;
}
Run Code Online (Sandbox Code Playgroud)
我的理解是,typedef意味着为类型赋予新的定义。通常,该typedef语句需要two-parts(或说两个参数)
第一部分是需要新别名的类型
第二部分是新的别名
typedef unsigned int UnsignedInt;
// ^ ^
// (original type) (Alias)
Run Code Online (Sandbox Code Playgroud)例如,在上面的代码中,第一部分是unsigned int,第二部分是UnsignedInt
typedef char * CharPtr;
// ^ ^
// (original type) (Alias)
Run Code Online (Sandbox Code Playgroud)
同样,在上面的第二个示例中,第一部分是char*,第二部分是CharPtr
问题:我typedef对函数指针的语句的FORMAT感到困惑。在语句中typedef int(*fp_GetBiggerElement)(int, int);,typedef没有遵循典型的两参数格式,那么它如何工作?
更新:我知道C ++ 11提供了另一种声明函数指针的方式,即(通过using声明)。在这个问题中,我只想了解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*
Run Code Online (Sandbox Code Playgroud)
与函数指针类似:
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)
Run Code Online (Sandbox Code Playgroud)
顺便说一下,在C ++ 11和进一步你不那么混乱(更强大)的替代typedef- using。您应该使用(双关语意)它。只是看看:
using fp = int (*)(int, int);// declare fp_t to be alias of pointer to int(int, int)
Run Code Online (Sandbox Code Playgroud)