Detailed C ++ function pointer

Detailed refer to the C ++ pointer: C ++ pointer to explain in detail

table of Contents

First, why there is a function pointer

Second, the function address

Third, the function pointer declaration

Fourth, use a pointer to call a function

Fifth, use typedef to simplify

appendix


First, why there is a function pointer

Similar data item is also a function of the address, in general, no use to the user, but for the program, use relatively large, for example: the address of a parameter as a function of another function, such a function to the first The second function is to find and run it. Although compared to direct calls more awkward than this way, but it allows the transfer address different functions at different times, which means you can use different functions at different times.

Second, the function address

The function name is the address of the function, for example: function get_sum (), the address of the function is get_sum instead get_sum (), get_sum () return value of the function.

Third, the function pointer declaration

Function pointer declaration: it indicates that the specified function returns the type, indicating the function of the signature (parameter list)

Note: Only when the same return type and parameter list and return type and parameter list of a function declaration function pointer when it can be passed, the compiler reject this assignment.

int get_sum(int a, int b);

int (*ptr)(int, int); // 声明函数指针ptr

Fourth, use a pointer to call a function

// 第一种方式
(*ptr)(4, 5);
// 第二种方式C++可用
ptr(4, 5);

Fifth, use typedef to simplify

For example: typedef double real; it means real is an alias that is real is equivalent to double the double.

#include<iostream>
#include<cstdio>
using namespace std;
int get_sum(int a, int b)
{
	return a+b;
}

int get_mul(int a, int b)
{
	return a*b;
}

int main()
{
	typedef int (*ptr)(int, int);
	ptr p1 = get_sum;
	cout<< p1(4, 5)<< endl;
	p1 = get_mul;
	cout<< p1(4, 5)<< endl;	
	
	return 0;		
}

appendix

/*
code_1
定义一个函数指针,然后调用,输出结果
*/
#include<iostream>
#include<cstdio>
using namespace std;
int get_sum(int a, int b)
{
	return a+b;
}

int get_mul(int a, int b)
{
	return a*b;
}

int main()
{
	int (*ptr)(int, int);
	
	ptr = get_sum;
	cout<< ptr(4, 5)<< endl;
	ptr = get_mul;
	cout<< ptr(4, 5)<< endl;
	
	return 0;		
}
/*
code_2
将函数指针作为一个函数的形参然后输出,并且说明两种输出方式表达的结果一致
*/
#include<iostream>
#include<cstdio>
using namespace std;
int get_sum(int a, int b)
{
	return a+b;
}

int get_mul(int a, int b)
{
	return a*b;
}

void show_result(int a, int b, int (*ptr)(int, 

int))
{
	cout<< ptr(a, b)<< endl;
	cout<< (*ptr)(a, b)<< endl;
}

int main()
{
	show_result(4, 5, get_sum);
	show_result(4, 5, get_mul);
		
	return 0;		
}

 

Published 331 original articles · won praise 135 · views 110 000 +

Guess you like

Origin blog.csdn.net/Triple_WDF/article/details/104185130