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>(*)()'
任何建议。或至少链接指向如何使用功能指针的详细站点。我正在使用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();
}
相关文章:
- 使用指向成员的指针将成员函数作为参数传递
- 如何使用Visual Studio 2017在C++中为参数化对象数组使用唯一指针
- 修改函数中的指针(将另一个指针作为参数传递)
- Clang bug?使用指针作为模板参数
- MSVC将仅移动结构参数解释为指针
- 非类型指针和引用模板参数,以及在编译时如何/为什么解析它们.c++
- 如何使用非类型模板参数传入指向数组的指针
- 将成员函数指针作为参数传递给模板方法
- 匹配函数指针作为模板参数?
- 当指向对象的指针作为参数传递给 std::thread 时,内存可见性
- 通过智能指针和转换对基本模板参数进行模板推导
- 为函数定义符号不明确的指针参数
- 使用引用与指针将数组作为参数传递
- 如何将成员函数作为回调参数传递给需要"typedef-ed"自由函数指针的函数?
- C++ - 声明指向返回任何类型并获取任意数量参数的函数的指针
- 将函数参数完美转发到函数指针:按值传递呢?
- 保留函数指针模板参数
- 如何构造一个以可变参数指针函数作为成员的类?
- 指向对象的非类型模板参数指针
- c++ 使用 *& as 参数(指针乐趣,三级树方法)