C 功能指针作为参数

C++ Function Pointer as Argument

本文关键字:参数 指针 功能      更新时间:2023-10-16

我尝试了多次Google搜索和帮助指南,但是我对此有所不可能。我有一个功能指针,我将其用作另一个功能的参数。这两个功能都在同一类中。但是,我不断遇到类型转换错误。我敢肯定这只是一个语法问题,但我不明白正确的语法是什么。这是我的代码的简化版本:

标题文件

#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进行编译。

您的总和函数期望指向一个函数。然后,您尝试使用指向成员函数的指针来调用它。了解成员的指针。

代码本身有点混乱,我只能纠正语法器以使其正常工作。

首先,您应从

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

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

如何将函数作为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));

lambdas:

func([](){});

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

void ff(std::function<void(void)> func) {
  func();
}