且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将一个类的函数作为参数传递给同一类的另一个函数

更新时间:2023-11-09 23:17:58

查看错误的位置。我敢打赌,它不在函数声明行上,而是在调用它的方式上。



观察:

  struct foo 
{
void bar(void(foo :: * func)(void));
void baz(void)
{
bar(& foo :: baz); //注意地址的获取方式
bar(& baz); //这是错误的
}
};






由于您在错误地调用该函数。鉴于以上我的 foo ,我们知道这行不通: baz(); // foo ::去哪里了?

因为 baz 需要调用一个实例上。您需要给它一个(我假设 this ):

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

语法有点怪异,但此运算符-> * 说:取右边的成员函数指针,并用左边的实例调用它。 (还有一个。* 运算符。)


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

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