c++ - 在 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
(或说两个参数)
第一部分是需要新别名的类型
第二部分是一个新的别名
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++ - 使用 ScrollWindowEx winapi 滚动部分矩形
- c# - BlockingCollection Take() 永远阻塞
- ruby-on-rails - Rails 5: FriendlyId TypeError (错误的参数类型 Symbol (expected Module:))
- docker - 使用 macvlan 驱动程序时如何从同一网络上的不同主机访问容器
- python - 如何在 Fedora 服务器上部署烧瓶应用程序?
- android - 对较低 API 的样式和主题支持
- mule - 通过某些值过滤有效负载并删除其他整个有效负载
- android - onPostExecute() 不等待线程在 doInBackground() 中完成?
- ios - CoreAnimation — 在动画开始之前图层闪烁到最终值?
- three.js - 平滑网格上的 Three.js SSAO 产生平面阴影结果