繁体   English   中英

C ++函数指针作为参数

[英]C++ Function Pointer as Argument

我已经尝试过多种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>(*)()'

任何建议表示赞赏。 或至少是有关如何使用函数指针的完整站点的链接。 我正在使用通过GCC编译的Qt Creator 2.6.2。

您的Sum函数需要指向函数的指针。 然后尝试使用指向成员函数的指针来调用它。 了解有关成员的指针。

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

首先,您应该将功能原型从

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

如何在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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM