C++学习笔记 26 函数指针
一、原始函数指针(raw function pointer)
函数指针:将一个函数赋值给一个变量的方法。
- 来自C语言
- 你可以把函数赋值给变量, 从这点出发,可以将函数作为参数传递给其他函数,也可以作为返回值
3.auto关键字对函数指针非常有用
#include<iostream>
#include<vector>
void HelloWorld() {
std::cout << "Hello World" << std::endl;
}
void HelloWorld2(int a) {
std::cout << "Hello World ! value: " << a << std::endl;
}
void basicFuntionPointer() {
//auto functionPointer = HelloWorld(); //调用并获取返回值,报错
//去掉括号,并不是调用函数了,而是获取函数指针
//函数只是CUP指令,当我们编译代码时,它(函数)就在二进制文件的某个地方。
//当你编译你的代码时,每个函数都被编译成CPU指令,它们就在我们的二进制文件中,可执行文件中。函数被调用时,检索要执行的指令位置。
//此处用&取地址的含义就是:在这个可执行文件中, 找到这个HelloWorld函数,获取这个CPU指令的内存地址
//auto functionPointer = &HelloWorld;
//我们实际上并没有用&,因为这里有一个隐式的转换。
auto functionPointer = HelloWorld;
functionPointer();
functionPointer();
//实际类型:void(*)(); 但是需要有一个名字
//void(*functionPointer)();
//等同于auto nihao = &HelloWorld; 或 auto nihao = HelloWorld;
void(*nihao)() = HelloWorld;
nihao();
}
//最常规用法:取别名,无参
void aliasFuntionPointerNoParams() {
typedef void(*HelloWorldFunction)();
HelloWorldFunction function = HelloWorld;
function();
}
//最常规用法:取别名,有参
void aliasFuntionPointerWithParams() {
typedef void(*HelloWorld2Function)(int);
HelloWorld2Function function2 = HelloWorld2;
function2(2);
}
//函数指针的实际用例
void PrintValue(int value) {
std::cout << "Value:" << value << std::endl;
}
void ForEachVector(const std::vector<int>& vec, void(*func)(int)) {
for (int value : vec) {
func(value);
}
}
void functionPrintVector() {
std::vector<int> vec = { 1, 2, 3, 4, 5 };
ForEachVector(vec, PrintValue);
}
//lambada本质就是一个普通函数,只是不像普通函数那样声明,它是在我们的代码过程中生成,用完即弃的匿名函数
void lambadaFunc() {
std::vector<int> vec = { 1, 2, 3, 4, 5 };
//[] 在这里叫捕获方式,也就是如何传入传出参数
ForEachVector(vec, [](int value) {
std::cout << "Value:" << value << std::endl;
});
}
int main() {
basicFuntionPointer();
aliasFuntionPointerNoParams();
aliasFuntionPointerWithParams();
functionPrintVector();
std::cin.get();
}

浙公网安备 33010602011771号