不兼容的函数指针

huangapple go评论78阅读模式
英文:

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(&amp;A::method2_of_A, a))

当然,最明确的意图在 @John 的评论中,其中你知道期望的是 A 的成员函数:

void methodB(void (A::*function)()) { (this-&gt;*function)(); }
英文:

Parameter void (*)() can only accept a free function.

If you have parameter std::function&lt;void()&gt;, it can call any callable, so you can adapt your member function with a lambda capturing the object and pass that

B.methodB([&amp;a](){ a.method2_of_A(); })

or binding the member function to the object (including &lt;functional&gt;)

B.methodB(std::bind(&amp;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-&gt;*function)(); }

huangapple
  • 本文由 发表于 2023年3月31日 17:10:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75896716.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定