zoukankan      html  css  js  c++  java
  • [58节] 函数指针 (Function Pointers in C++)

    来看一个例子

    #include <iostream>

    void
    HelloWorld() { std::cout << "Hello World" << std::endl; } int main() { void(*function)(); function = HelloWorld; function(); std::cin.get(); }

    这个例子里,如果我们把函数名给一个auto,那么其实就是在创建一个函数指针,它的类型就像上面的例子这样,这样写可能比较迷惑,所以换一个写法,它可能是这样的

    int main()
    {
    
        typedef void(*HelloWorldFunction)();
    
        HelloWorldFunction function = HelloWorld;
    
        function();
    
        std::cin.get();
    }

    我们接下来增加参数

    #include <iostream>
    
    void HelloWorld(int a)
    {
        std::cout << "Hello World,the Value is "<< a << std::endl;
    }
    
    int main()
    {
    
        typedef void(*HelloWorldFunction)(int);
    
        HelloWorldFunction function = HelloWorld;
    
        function(8);
    
        std::cin.get();
    }

    这差不多是函数指针全部的功能,接下来我们举一个例子,为什么我们首先要使用函数指针。

    #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);
        std::cin.get();
    }

    在这个情况下, 我们需要给ForEach函数传递一个函数指针,让它能够去使用PrintValue函数。

    我们也可以写成lamda表达式,总之放上这样一个例子

    #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; });
        std::cin.get();
    }
  • 相关阅读:
    jieba库与词云的使用——以孙子兵法为例
    Python 计算π及进度条显示
    风车
    UDP协议编程
    matplotlib的基本使用、绘制雷达图及绘制数学函数
    numpy库的学习笔记及自定义手绘风
    PIL库的学习总结及生成GIF
    预测球队比赛结果及利用pyinstaller打包文件
    汉诺塔的实现
    有进度条的圆周率计算
  • 原文地址:https://www.cnblogs.com/EvansPudding/p/12539371.html
Copyright © 2011-2022 走看看