在之前的笔记中我们学过了指针,我们说int* a指向的是地址,地址处存放的数据是int类型。对变量取地址&a,对变量赋值*a = 2;
本次我们先从C中函数指针开始。
在以前我们编写函数时我们输入参数往往是(int、char 、std::string、int*等等),那么函数可不可以作为参数传递呢?可以的。让我们从简单的栗子看
#include <iostream>
void Printf()
{
std::cout<<"Hello"<<std::endl;
}
int main()
{
auto Function = Printf;//void(*Function)() = Printf;
Function();
Function();
std::cin.get();
}
Printf()表示函数,去掉()后,Printf表示的就是函数指针,将其赋值给Function。你可能要问Function什么数据类型?是char*吗?并不是插入*,而是void(*Function)()。那我们为什么要用auto呢?auto关键字含义是自动计算数据类型,举个栗子。
#include <iostream>
int main()
{
int a = 2;
auto b = a;
std::cout<<a<<","<<b<<std::endl;
std::cin.get();
}
以上打印出的是
2,2
我们可以看到对于b我们并没有规定其数据类型,然而auto自动更新其类型最后打印出2,2
回到上一个代码块,auto计算出的类型就是void(*Function)();
对于有参数的函数怎么用函数指针?以下栗子。
#include <iostream>
void Printf(int a)
{
std::cout<<"Hello"<<a<<std::endl;
}
int main()
{
auto Function = Printf;//void(*Function)(int) = Printf;
Function(6);
Function(8);
std::cin.get();
}
void(*Function)(int) = Printf;在第二个括号加入数据输入参数类型即可。我们学会了使用函数指针,回到第一个问题,函数可不可以作为参数传递呢?以下栗子。
#include <iostream>
#include <vector>
void PrintfVer(int ver)
{
std::cout<<"ver is"<<ver<<std::endl;
}
void ForEach(const std::vector& vers,void(*func)(int))
{
for(int ver:vers)
func(ver);
}
int mian()
{
std::vector<int> V = {1,5,4,2,3};
ForEach(V,PrintfVer);
std::cin.get();
}
打印效果
ver is 1
ver is 5
ver is 4
ver is 2
ver is 3
我们创建动态数组并将PrintfVer作为参数打印数据。
void PrintfVer(int ver)是一个具有参数的函数。
void ForEach(const std::vector& vers,void(*func)(int))具有两个参数第一个参数是动态数组,第二个参数是函数指针,目的是打印数组中内容。其内部用的for循环也是动态数组的特性自行去观看动态数组这个笔记哦。
以上就是函数指针以及auto的使用方法,今天巴黎奥运,断更两天~~~~~