【问题标题】:How do you pass a function of a class as a parameter to another function of the same class如何将一个类的函数作为参数传递给同一个类的另一个函数
【发布时间】:2011-03-31 04:36:41
【问题描述】:

我基本上想使用一个 diff 函数来提取一个类 (ac) 的不同元素。

代码类似这样:

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

没有用,它给出了错误#547“获取成员函数地址的非标准形式”

编辑:

我叫它:

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

但是,我还有另一个错误:

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

【问题讨论】:

  • 这看起来像一个函数定义,但错误听起来像是你在形成指向成员的指针时遇到了问题。您也可以发布该代码吗?
  • 您应该使用typedef(如typedef double (MyClass::*F1Func)(AnotherClass &amp;);),这样该类的用户就不会被声明所迷惑——void MyClass::f0(F1Func f1)void MyClass::f0(double(MyClass::*f1)(AnotherClass &amp;)); 更具可读性跨度>
  • 我不相信您从网站打来的电话。如果MyClass 是类的名称,则不能有void MyClass(AnotherClass &amp; ac)。对于您的其他错误,您是否阅读了我的答案的第一部分?

标签: c++ class function-pointers member-function-pointers


【解决方案1】:

查看错误指向的位置。我敢打赌,这不是函数声明行,而是你如何调用它。

观察:

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
    }
};

您收到错误是因为您错误地调用了该函数。鉴于我上面的foo,我们知道这行不通:

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

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

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

语法有点奇怪,但是这个操作符-&gt;* 说:“取右边的成员函数指针,用左边的实例调用它。” (还有一个.* 运算符。)

【讨论】:

    【解决方案2】:

    您仍然没有发布创建指向成员的指针的代码,这似乎是错误的原因,但是您如何使用它存在问题。

    要使用指向成员的指针,您需要使用-&gt;*.* 运算符之一,并带有指向适当类实例的指针或引用。例如:

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

    你可以这样调用函数:

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

    请注意,对于指向成员的指针,您需要&amp;,这与隐式转换为函数指针的普通函数名称不同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-18
      • 1970-01-01
      • 2013-04-13
      • 1970-01-01
      • 2023-01-18
      • 2017-08-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多