将函数作为指针传递时,如何指定参数?

时间:2015-06-03 05:29:02

标签: c++

我发现了很多关于函数指针的信息,但有一点真的让人困惑。我该如何指定正在传递的函数的参数?我一直试图做的一个例子......

void BatchDelete(string head, string filename, void (*f)(string, string));
void DeleteOneNode(string head, string song);
BatchDelete(head, filename, DeleteOneNode)

从我所看到和看到的,当传递一个函数时,它应该永远不会有括号,因为这是一个函数调用,但是如何指定两个字符串DeleteOneNode得到什么?

1 个答案:

答案 0 :(得分:4)

你不是。函数指针是指向要调用的函数的指针,由调用站点提供参数。

#include <iostream>

void target(const std::string& str)
{
    std::cout << "fn " << str << "\n";
}

void caller(void (*fn)(const std::string&))
{
    fn("hello world");
}

int main()
{
    caller(target);
}

现场演示:http://ideone.com/AWsxk5

在您提供的示例中,BatchDelete采用一些参数来查找歌曲,然后根据需要调用您的回调函数,为您传递它们 - 您不必担心试图传递它们。

那是函数指针的重点,它找到要删除的文件,但是它希望你提供函数do to delete,更重要的是,函数指针的目的是关于来自中间函数的收据的合同。

---编辑---

更多&#34; batchdelete&#34;喜欢这个例子的版本:

#include <iostream>

void callbackfn(std::string path, std::string filename)
{
    std::cout << "delete " << path << "\\" << filename << "\n";
}

void BatchDelete(std::string path, std::string file, void (*fn)(std::string, std::string))
{
    // pretend these are songs we found in playlist.mpl
    fn(path, "Alanis\\*.*");
    fn(path, "Mix Tape\\ReallySadSong.mp3");
}

int main()
{
    BatchDelete("C:\\Music\\", "playlist.mpl", callbackfn);
}

http://ideone.com/NEpXeC