我理解类似questions with answers之前已经被问过。我已经了解函数指针的概念及其声明的含义。以下是我的函数指针的示例代码,我在其中分配了函数指针 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
(或者说两个参数)
第一部分是需要新别名的类型
第二部分是新的别名
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
的语法函数指针的声明。
最佳答案
我认为考虑 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)
关于c++ - C++ 中函数指针 typedef 的声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58390123/