英文:
Incompatible function pointer
问题
I am creating an instance of class B in a method of class A (which is a QMainWindow) with B instanceB;
and then call a method of B with B.method()
and pass it the function pointer of a method of A.
Now the compiler says "argument of type "void (A::)()" is incompatible with parameter of type "void ()()". How do I resolve this if possible?
Code:
void A::method1_of_A(void)
{
B instanceB;
B.methodB(method2_of_A); // this is where the compiler complains
}
英文:
I am creating an instance of class B in a method of class A (which is a QMainWindow
) with B instanceB;
and then call a method of B with B.method()
and pass it the function pointer of a method of A.
Now the compiler says argument of type "void (A::*)()" is incompatible with parameter of type "void (*)()"
. How do I resolve this if possible?
Code:
void A::method1_of_A(void)
{
B instanceB;
B.methodB(method2_of_A); // this is where the compiler complains
}
答案1
得分: 2
Parameter void (*)()
只能接受自由函数。
如果你有参数 std::function<void()>
,它可以调用任何可调用对象,所以你可以使用 lambda 来适应你的成员函数,捕获对象并传递它:
B.methodB([&a](){ a.method2_of_A(); })
或者将成员函数绑定到对象(包括 <functional>
):
B.methodB(std::bind(&A::method2_of_A, a))
当然,最明确的意图在 @John 的评论中,其中你知道期望的是 A 的成员函数:
void methodB(void (A::*function)()) { (this->*function)(); }
英文:
Parameter void (*)()
can only accept a free function.
If you have parameter std::function<void()>
, it can call any callable, so you can adapt your member function with a lambda capturing the object and pass that
B.methodB([&a](){ a.method2_of_A(); })
or binding the member function to the object (including <functional>)
B.methodB(std::bind(&A::method2_of_A, a))
Of course, clearest intent is in @John's comment, where you know a member function of A is expected:
void methodB(void (A::*function)()) { (this->*function)(); }
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论