2017-04-21 18 views
0

所以,我想傳遞的功能,那就是在engine.cpp文件,作爲參數,這就是我所做的:傳遞函數作爲參數傳遞給不同的功能在不同的文件

typedef RFun(*wsk)(double, int); 

RFun Engine::f_line(double *&values, int howmany) 
{ 
    RFun line; 

    for(int i = 0; i < howmany; i++) 
    { 
     line.result_values[i] = (2 * values[i]) + 6; 
    } 

    return line; 
} 

RFun counter(double *&values, int howmany, wsk function) 
{ 
    return function(*values, howmany); 
} 

,現在我想要在其他.cpp文件中調用計數器函數並將f_line函數作爲參數傳遞給它。我怎樣才能做到這一點?

+1

[std :: function](http://en.cppreference.com/w/cpp/utility/functional/function)想起來... –

+1

它看起來像我,就像你打算用'wsk'函數指針傳遞'Engine :: f_iline'。如果是這種情況,由於參數類型不匹配,會遇到困難('double'和'double *&'不相同)並且'Engine :: f_file'是一個成員函數,它與指向函數的指針不兼容。你需要一個指向成員函數的指針。 –

+1

澄清@FrançoisAndrieux所說的話:'&f_line'類型是'RFun(Engine :: *)(double *&,int)',而不是'RFun(*)(double,int)'。 –

回答

2

這裏是一個簡單的example如何使用std :: function。在memberfunc 0

全球FUNC1 :

#include <iostream> 
#include <functional> 
using namespace std; 

void func1() 
{ 
    // a function that takes no parameters and does nothing 
    cout << "in global func1" << endl; 
} 

class Example 
{ 
public: 
    int value; 

    void memberfunc() 
    { 
    cout << "in memberfunc. value=" << value << endl; 
    } 
}; 

void CallAFunction(std::function< void() > functocall) 
{ 
    functocall(); // call it normally 
} 

int main() 
{ 
    // call a global function 
    CallAFunction(func1); // prints "in global func1" 

    // call a member function (a little more complicated): 
    Example e; 
    e.value = 10; 
    CallAFunction(std::bind(&Example::memberfunc, std::ref(e))); 
    // prints "in memberfunc. value=10" 
} 

試試吧here

成功時刻:0記憶:15240信號。值= 10

+0

好的,但我必須傳遞一些參數給我的函數。 –

+0

@MikołajPopieluch在這裏看到:http://stackoverflow.com/questions/19691934/passing-member-function-with-all-arguments-to-stdfunction – Beginner

相關問題