#include <iostream>
#include <vector>
// functions are just CPU instructions, somewhere in the executable file.
// raw style function pointer comes from c.
// it's a way to assign a function to a variable.
void Function() { }
void HelloWorld(int a)
{
std::cout << "HelloWorld! Value = " << a << std::endl;
}
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(void)
{
here the type of auto is: void(*functionPointer0)(int)
//auto functionPointer0 = Function;//create a function pointer.
//functionPointer0;//call a function pointer.
// instead of using auto, create an alias for it.
typedef void(*HelloWorldFunction)(int);
HelloWorldFunction functionPointer1 = HelloWorld;
functionPointer1(5);
// an actually useful example.
std::vector<int> values = {1, 4, 5, 6, 8};
//ForEach(values, PrintValue);// have to declare a function.
// or use a lambda, an anonymous function.
ForEach(values, [](int value){ std::cout << "Value = " << value << std::endl; });
std::cin.get();
}
【Cherno的C++视频】Function pointers in C++
最新推荐文章于 2024-10-18 22:48:33 发布