【发布时间】:2025-12-02 18:45:02
【问题描述】:
我已经尝试了多个谷歌搜索和帮助指南,但我对这个没有想法。我有一个函数指针,用作另一个函数的参数。这两个函数都在同一个类中。但是,我不断收到类型转换错误。我确定这只是一个语法问题,但我不明白正确的语法是什么。这是我的代码的简化版本:
头文件
#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 编译。
【问题讨论】:
-
这不仅仅是任何旧功能。它是一个 member 函数。
-
将
complex<double>(*arg1)(void)更改为complex<double>(T::*arg1)(void) -
我相信你会这样称呼它
out += (this->*arg1)();
标签: c++ function pointers arguments