如何将函数指针传递给成员函数c ++?

时间:2017-10-29 13:31:01

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

所以这就像我关于这个主题的第二个问题,但是这次我想知道如果我传递一个int类型的函数会怎样。就像这里我想将fun1的输出存储在变量" int my&# 34;在主要功能。我该如何为此编写包装函数?

#include<iostream>
using namespace std;

class student
{
public:
    int fun1(int m) 
    { 
        return 2*m;
    }

    int wrapper(int (student::*fun)(int k))
    {
        (this->*fun)(int k)
    }
};

int main()
{   
    student s;
    int l=5;
    int my=s.wrapper(&student::fun1(l));
    cout << m << endl;
    return 0;
}

2 个答案:

答案 0 :(得分:3)

包装调用者需要两个参数:
一个用于调用函数,一个用于调用 使用

调用它的参数
def count(sentence):
    wlist = []
    word = ""
    for c in sentence:
        if c == " ":
            wlist.append(word)
            word = ""
        else:
            word += c
    wlist.append(word)
    return len(wlist)

称之为:

int wrapper(int (student::*fun)(int), int k)
{
    return (this->*fun)(k);
}

在此处查看http://coliru.stacked-crooked.com/a/cd93094c38bfa591

答案 1 :(得分:1)

在标准库中提供mem_fn()时,为什么还要创建自己的包装器:

int my = mem_fn(&student::fun1)(&s,l);
cout<<my<<endl;

Online demo