How do you pass a function of a class as a parameter to another function of the same class

ε祈祈猫儿з 提交于 2019-12-04 18:19:57

Look at where the error points. I bet it's not on the function declaration line, but on how you call it.

Observe:

struct foo
{
    void bar(void (foo::*func)(void));
    void baz(void)
    {
        bar(&foo::baz); // note how the address is taken
        bar(&baz); // this is wrong
    }
};

You're getting your error because you're calling the function incorrectly. Given my foo above, we know this won't work:

baz(); // where did the foo:: go?

Because baz requires an instance to be called on. You need to give it one (I'll assume this):

std::cout << (this->*f1)(ac);

The syntax is a bit weird, but this operator ->* says: "take the member function pointer on the right, and call it with the instance on the left." (There is also a .* operator.)

You still haven't posted the code where you create the pointer to member which is what the error seems to be about, but there is an issue with how you use it.

To use a pointer to member you need to use one of ->* or .* operators with a pointer or reference to an appropriate instance of the class. E.g.:

void MyClass::f0(AnotherClass & ac, double(MyClass::*f1)(AnotherClass &))
{
  std::cout << (this->*f1)(ac);
}

You can call the function like so:

void f()
{
    AnotherClass ac;
    MyClass test;
    test.f0( ac, &MyClass::f1 );
}

Note that for pointers to members you need &, unlike normal function names which convert implicitly to function pointers.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!