C++创建一个被指向作为参数的函数

C++ Creating a function that is being pointed to as an argument

本文关键字:参数 函数 创建 一个 C++      更新时间:2023-10-16

所以这很难解释,但我会尽我所能。

我有一个函数,我的一个类将函数指针作为参数,我想做的是将函数定义为参数的一部分。即:

object->setFunctionPointer({string a = ""; return a;});

这可能吗?如果是的话,正确的语法是什么?

在C++11中,你可以做到这一点。你可以使用C++lambda(匿名函数)。

请参阅上的示例代码http://ideone.com/8ZTWSU

#include <iostream>
using namespace std;
typedef const char * (*funcptr)();
funcptr s;
void setFuncPtr(funcptr t)
{
    s = t;
}
int main() {
    // your code goes here
    setFuncPtr([]{return "Hello n"; });
    printf("%sn", s());
    return 0;

}

如果我们谈论C++,应该使用std::函数,而不是函数指针。除非您正在与C API接口。

class Foo{
SetFunc(std::function<void(int)> func)
{
    m_func = func;
} 
private:
std::function<void(int)> m_func;
};

如果函数是类的成员,则不能使用普通函数指针来存储其地址。你需要的是一名代表;它们是用于方法的专用函数指针。在互联网上搜索C++代表,你会发现很多例子。

(注意:静态方法可能有一个例外;我不记得了。)

这里有一个完整的例子。由于c++11,这就是前进的道路:

#include<functional> 
#include<string> 
#include<iostream> 
using namespace std;
class Object
{
    public: 
        void setFunctionPointer(function<string(void)> function)
        {
            m_function = function;
        }
        string run()
        {
            return m_function();    
        }
    private:
        function<string(void)> m_function;
};
int main(int argc, char**argv)
{
    Object *object = new Object;
    object->setFunctionPointer([]{string a = "FOO"; return a;}); // here is the function assignment 
    cout << object->run() << endl;
    delete object;
}

运行此程序时,会将FOO打印到stdout。