C ++函数指针作为参数

时间:2014-01-24 01:10:58

标签: c++ function pointers arguments

我尝试过多次谷歌搜索和帮助指南,但我对此没有想法。我有一个函数指针,我用它作为另一个函数的参数。两个函数都在同一个类中。但是,我不断收到类型转换错误。我确定这只是一个语法问题,但我无法理解正确的语法是什么。这是我的代码的简化版本:

头文件

#ifndef T_H
#define T_H

#include <iostream>
#include <complex>

namespace test
{

class T
{
public:
    T();
    double Sum(std::complex<double> (*arg1)(void), int from, int to);
    int i;
    std::complex<double> func();
    void run();
};

}
#endif // T_H

源文件

#include "t.h"

using namespace test;
using namespace std;

//-----------------------------------------------------------------------
T::T()
{
}

//-----------------------------------------------------------------------
double T::Sum(complex<double>(*arg1)(void), int from, int to)
{
    complex<double> out(0,0);

        for (i = from; i <= to; i++)
        {
            out += arg1();
            cout << "i = " << i << ", out = " << out.real() << endl;
        }

    return out.real();
}

//-----------------------------------------------------------------------
std::complex<double> T::func(){
    complex<double> out(i,0);
    return out;
}

//-----------------------------------------------------------------------
void T::run()
{
    Sum(&test::T::func, 0, 10);
}

每当我尝试编译时,都会收到以下错误:

no matching function for call to 'test::T::Sum(std::complex<double> (test::T::*)(),int,int)'
note:  no known conversion for argument 1 from 'std::complex<double> (test::T::*)()' to 'std::complex<double>(*)()'

任何建议表示赞赏。或者至少是一个关于如何使用函数指针的完整站点的链接。我正在使用Qt Creator 2.6.2,使用GCC进行编译。

3 个答案:

答案 0 :(得分:3)

您的Sum函数需要指向函数的指针。然后你尝试用指向成员函数的指针调用它。了解指向会员的指示。

答案 1 :(得分:1)

代码本身有点乱,我只会更正语法才能使其正常工作。

首先,您应该从

更改函数原型
double Sum(std::complex<double> (*arg1)(void), int from, int to);

double Sum(std::complex<double> (T::*arg1)(void), int from, int to);

这意味着它是指向T类成员的指针。

然后,在调用该函数时,您只能arg1()

for (i = from; i <= to; i++)
{
    out += arg1();
    cout << "i = " << i << ", out = " << out.real() << endl;
}

你必须使用(this->*arg1)();

for (i = from; i <= to; i++)
{
    out += (this->*arg1)();
    cout << "i = " << i << ", out = " << out.real() << endl;
}

答案 2 :(得分:1)

如何在C ++中将函数作为参数传递?一般来说,使用模板,除非你有非常令人信服的理由不这样做。

template<typename Func>
void f(Func func) {
  func(); // call
}

在通话方面,你现在可以输入一定数量的对象(不只是指向函数的指针):

函子;

struct MyFunc {
  void operator()() const {
    // do stuff
  }
};

// use:
f(MyFunc());

普通功能:

void foo() {}

// use
f(&foo) {}

会员职能:

struct X {
  void foo() {}
};

// call foo on x
#include <functional>
X x;
func(std::bind(&X::foo, x));

lambda表达式:

func([](){});

如果您真的想要编译函数而不是模板,请使用std::function

void ff(std::function<void(void)> func) {
  func();
}
相关问题