1

我基本上想使用一个差异函数来提取一个类(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
4

2 回答 2

4

看看错误点在哪里。我敢打赌它不在函数声明行,而是在你如何调用它。

观察:

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

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

于 2010-08-17T19:36:57.330 回答
1

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

要使用指向成员的指针,您需要使用其中一个->*.*运算符与指针或对类的适当实例的引用。例如:

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

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

于 2010-08-17T19:49:53.333 回答