【问题标题】:Passing a member function as arguments using pointer-to-member-function C++使用指向成员函数 C++ 的指针将成员函数作为参数传递
【发布时间】:2016-06-24 16:11:27
【问题描述】:

我正在尝试使用pointer-to-member-function 将成员函数作为参数传递。我已经看到了一些类似here 的链接,但我无法解决问题。

Foo 类有两个成员函数。我需要将addition 函数作为参数传递给NewOper 函数。 这是我的代码。我可以正确地使用指针来调用addition 函数,但是当我尝试将它作为参数传递给NewOper 函数时它给了我一个错误。如果您告诉我如何解决它,我将不胜感激。 (最后两行导致错误)

#include <iostream>
using namespace std;
class Foo{
public:
    int addition(int a, int b)
    {
        return (a + b);
    }

    int NewOper(int x, int y, int(*fnc2call)(int, int))
    {
        int r;
        r = (*fnc2call)(x, y);
        return (r);
    }
};
int main()
{
    int m,n, k, l;
    int (Foo::*fptr) (int, int) = &Foo::addition;
    Foo obj;
    m=(obj.*fptr)(1,2);
    Foo* p = &obj;
    n=(p->*fptr)(3,4);
    cout << m << endl;
    cout << n << endl;
    //**********************
    int (Foo::*fptr) (int, int, int(*fnc2call)) = &Foo::NewOper;
    k = (obj.*fptr)(1, 2, addition);
}

【问题讨论】:

  • 这看起来很相似:stackoverflow.com/questions/130322/… 不过我不太确定它是重复的。
  • Foo::addition 必须是 static 才能传递给 NewOper
  • 您的问题是关于哪一部分?为什么你把最后两行注释掉了?
  • @Barmar,我的问题是关于最后两行。我取消了它们的注释。这两行给了我错误。
  • 请记住,成员函数也将其this 指针作为隐藏参数,因此普通函数点无法使用它们。

标签: c++ function pointers member


【解决方案1】:

您已经在自己的代码中找到答案:

int (Foo::*fptr) (int, int) = &amp;Foo::addition - 在这里您正确地将fptr 声明为指向函数的指针,它是类Foo 的(非静态)成员

但是你忘了在你NewOper函数定义中做同样的事情:

int NewOper(int x, int y, int(*fnc2call)(int, int)) - 此函数需要 free 函数的地址作为第三个参数。以与声明 fptr 相同的方式重新定义它。但是你还需要将指向类 Foo 对象的指针传递给这个函数

或者,您可以按照 Jarod42 的建议将您的函数 addition 设为静态(实际上,按照现在的编写方式,没有理由让它成为 Foo 类的成员,除非您有进一步的计划)。然后你需要从fptr 定义中删除Foo::

【讨论】:

    猜你喜欢
    • 2020-06-09
    • 2012-07-22
    • 2013-06-29
    • 2013-08-11
    • 2012-06-27
    • 1970-01-01
    • 2017-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多