LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 195|回复: 0

指向函数的指针

[复制链接]
发表于 2024-2-4 23:24:18 | 显示全部楼层 |阅读模式
在 C 风格的编程中,函数指针主要用于将函数传递给其他函数。 此方法使调用方能够在不修改函数的情况下自定义函数的行为。 在新式 C++ 中,lambda 表达式提供了相同的功能,并且提供了更高的类型安全性和其他优势。

函数指针声明指定指向函数必须具有的签名:

// Declare pointer to any function that...

// ...accepts a string and returns a string
string (*g)(string a);

// has no return value and no parameters
void (*x)();

// ...returns an int and takes three parameters
// of the specified types
int (*i)(int i, string s, double d);
以下示例展示了函数 combine,该函数将接受 std::string 并返回 std::string 的任何函数作为参数。 根据传递给 combine 的函数,它将在前面或后面添加字符串。

#include <iostream>
#include <string>

using namespace std;

string base {"hello world"};

string append(string s)
{
    return base.append(" ").append(s);
}

string prepend(string s)
{
    return s.append(" ").append(base);
}

string combine(string s, string(*g)(string a))
{
    return (*g)(s);
}

int main()
{
    cout << combine("from MSVC", append) << "\n";
    cout << combine("Good morning and", prepend) << "\n";
}

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表