C++关键字 typedef 的不同用法说明,含函数引用和函数指针

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值