函数指针是将一个函数赋值给一个变量的方法

函数指针是什么

#include<iostream>
 
void helloWordl(int a)
{
	std::cout << "Hello World! Value: " << a << std::endl;
}
 
int main(){
	auto function = helloWordl();//函数名加上括号表示函数调用,左侧变量只能与函数返回参数类型保持一致
	auto function1 = helloWordl;//只有函数名,左侧变量接收的是函数指针,例如&helloWorld
	
	typedef void(*HelloWorldFunction)(int);
	HelloWorldFunction function = helloWordl;
	
	function(2);
}

函数指针怎么用

#include<iostream>
#include<vector>
 
void PrintValue(int value)
{
	std::cout << "Value: " << value << std::endl;
}
 
void ForEach(const std::vector<int>& values, void(*func)(int))
{
	for(int value:values)
		func(value);
}
 
int main()
{
	std::vector<int> values = {1,5,4,2,3};
	ForEach(values,PrintValue);
}

通过函数指针,可以指定遍历数组时对每个成员进行的操作

#include<iostream>
#include<vector>
 
void ForEach(const std::vector<int>& values, void(*func)(int))
{
	for(int value:values)
		func(value);
}
 
int main()
{
	std::vector<int> values = {1,5,4,2,3};
	ForEach(values,[](int value) {std::cout << "Value: " << value << std::endl;});
}

对于一个简单的功能,不需要专门定义一个函数,使用不需要声明的 lambda 函数,该函数在代码运行过程中生成,并且用完即弃,属于匿名函数