[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();
}

 

原文链接: https://www.cnblogs.com/EvansPudding/p/12539371.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    [58节] 函数指针 (Function Pointers in C++)

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/336685

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月1日 下午10:46
下一篇 2023年3月1日 下午10:46

相关推荐