C++ 为什么可以';在C++;?

C++ 为什么可以';在C++;?,c++,function,class,parameters,parameter-passing,C++,Function,Class,Parameters,Parameter Passing,因此,我试图在C++中通过我的两个类传递一个函数作为参数: void class1::func_1(QString str) { class2* r = new class2(); r->func_2(str, &process); } void class1::process(QString str) { //Do something with str } 其中'r->func_2'如下所示: QString class2::func_2(QStri

因此,我试图在C++中通过我的两个类传递一个函数作为参数:

void class1::func_1(QString str)
{
    class2* r = new class2();
    r->func_2(str, &process);
}

void class1::process(QString str)
{
     //Do something with str
}
其中'r->func_2'如下所示:

QString class2::func_2(QString str, void (*callback)(QString))
{
   //Do something else
}
但是,当我尝试编译时,会出现以下错误:

must explicitly qualify name of member function when taking its address
    r->func_2(str, &process);
                    ^~~~~~~~
                     class1::

cannot initialize a parameter of type 'void (*)(QString)' with an rvalue of type 'void (class1::*)(QString)'
    r->func_2(str, &process);
                    ^~~~~~~~

我不知道为什么。有什么想法吗?我显然做错了什么。。。只是不确定是什么。任何帮助都将不胜感激。谢谢

这些函数是成员函数,它们不是静态的。我建议您使用std::function和std::bind。通过这些,您将能够将函数作为参数。请记住,当您使用std::bind传入参数时,它不是一个静态/全局函数,而是某个对象的成员,您还需要使用称为placement的东西。查一查。顺便说一下,您不需要使用lambdas

class A
{
    std::string m_name;
    void DisplayName() { std::cout << m_name };
}

void TakeFunctionAsArgument(std::function<void(void)> func)
{
    func();
}

int main()
{
    A objectA;
    TakeFunctionAsArgument(std::bind(&A::DisplayName, objectA));
    return 0;
}
A类
{
std::字符串m_名称;

void DisplayName(){std::cout传递成员函数名的地址时,需要完全限定其名称:

void class1::func_1(QString str)
{
    class2* r = new class2();
    r->func_2(str, &class1::process);
}

函数指针和成员函数指针是不同的类型。后者需要类的一个实例。你能使这些函数成为静态的吗?如果可以,那应该可以解决问题。如果不能,你需要研究
,或者使用C++11的lambdas。@dasblinkenlight:如果C++11可用,我建议使用或lambdas,如果不是的话,更喜欢boost版本的而不是静态版本。