typedef的说明
在Cppreference 网站中对typedef的解释中给出了实际用例。
https://en.cppreference.com/w/cpp/language/typedef
其中下面的部分较难理解,在这里对其进行拆解分析。
// more complicated typedef
typedef int int_t, *intp_t, (&fp)(int, ulong), arr_t[10];
实际上typedef int int_t, *intp_t, (&fp)(int, ulong), arr_t[10];
分解开之后就是:
typedef int int_t; //还是int
typedef int *intp_t; //int指针
typedef int(&fp)(int, long); //函数引用
typedef int arr_t[10]; //容量为10的int数组
其中,较难理解的是函数的引用,说白了typedef int(&fp)(int, long);
就是想对一个返回值为int的函数定义一个别名,以后用起来方便。
除了函数引用,实际上还有函数指针,typedef int(*fp)(int, long);
两者有些相似但又有区别。
下面的代码对包含函数指针和函数引用的typedef使用进行了示例:
#include <iostream>
using namespace std;
int myadd(int a, long b)
{
return a + b;
}
int main()
{
//typedef int int_t, *intp_t, (&fp)(int, long), arr_t[10];
typedef int int_t;
typedef int *intp_t;
typedef int(&fp)(int, long);
typedef int arr_t[10];
// the following two objects have the same type
int_t a1[3] = { 1,2,3 };
arr_t a2 = { 4,5,6 };
intp_t arrp = a2;
//function 函数引用
fp myfun = myadd; //myfun is another name of myadd
int n1 = myfun(a1[0], arrp[0]); //1+4=5
cout << "Result of function reference:" << n1 << endl; // 5
//more things 函数指针
typedef int(*fpp)(int, long);
fpp myfpp = &myadd;
int n2 = (*myfpp)(a1[1], arrp[1]); //2+5=7
cout << "Result of function pointer:" << n2 << endl; //output 7
system("pause");
}
关于函数引用,函数指针和模板template的深入使用分析,可以参考一下下面的博客。
https://www.cnblogs.com/overlows/p/10678979.html