How do you pass a function of a class as a paramet

2020-07-31 03:34发布

问题:

i basically want to use a dif function to extract a different element of a class (ac).

the code is similar to this:

.h:

class MyClass
{
  public:
    double f1(AnotherClass &);
    void MyClass::f0(AnotherClass & ac, double(MyClass::*f1)(AnotherClass &));
};

.cc:

double MyClass::f1(AnotherClass & ac)
{
  return ac.value;
}

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

didn't work, it gives error#547 "nonstandard form for taking the address of a member function"

EDIT:

I call it from:

void MyClass(AnotherClass & ac)
{
  return f0(ac,&f1);  // original and incorrect
  return f0(ac,&Myclass::f1); //solved the problem
}

However, I have another error:

std::cout << f1(ac); 
             ^ error: expression must have (pointer-to-) function type

回答1:

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.)



回答2:

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.