我在编译代码时遇到一些问题。 我有以下结构:
#include <cstdlib>
using namespace std;
typedef double (*FuncType)(int );
class AnotherClass {
public:
AnotherClass() {};
double funcAnother(int i) {return i*1.0;}
};
class MyClass {
public:
MyClass(AnotherClass & obj) { obj_ = &obj;};
void compute(FuncType foo);
void run();
protected:
AnotherClass * obj_; /*pointer to obj. of another class */
};
void MyClass::compute(FuncType foo)
{
int a=1;
double b;
b= foo(a);
}
void MyClass::run()
{
compute(obj_->funcAnother);
}
/*
*
*/
int main(int argc, char** argv) {
AnotherClass a;
MyClass b(a);
b.run();
return 0;
}
当我尝试编译它时,它给出:
main.cpp:39:31: error: no matching function for call to ‘MyClass::compute(<unresolved overloaded function type>)’
main.cpp:30:6: note: candidate is: void MyClass::compute(double (*)(int))
这里出了什么问题?
p/s/AnotherClass * obj_;
应该保持这样,因为我向大库写入了一些函数并且无法更改它。
-------------- 本杰明的工作版本 --------
#include <cstdlib>
using namespace std;
class AnotherClass {
public:
AnotherClass() {};
double funcAnother(int i) {return i*1.0;}
};
struct Foo
{
/*constructor*/
Foo(AnotherClass & a) : a_(a) {};
double operator()(int i) const
{
return a_.funcAnother(i);
}
AnotherClass & a_;
};
class MyClass {
public:
MyClass(AnotherClass & obj) { obj_ = &obj;};
template<typename FuncType>
void compute(FuncType foo);
void run();
protected:
AnotherClass * obj_; /*pointer to obj. of another class */
};
template<typename FuncType>
void MyClass::compute(FuncType foo)
{
int a=1;
double b;
b= foo(a);
}
void MyClass::run()
{
Foo f(*obj_);
compute(f);
}
/*
*
*/
int main(int argc, char** argv) {
AnotherClass a;
MyClass b(a);
b.run();
return 0;
}
非常感谢大家的帮助!
最佳答案
自从,
funcAnother(int i);
是一个成员函数,它传递隐式的this
,然后原型(prototype)与函数指针的类型不匹配。
指向成员函数的指针的 typedef 应该是:
typedef double (AnotherClass::*funcPtr)(int);
<强> Here 是代码的修改后的可编译版本。请检查内联评论以了解更改,另外我省略了其他详细信息,您可以添加。
关于c++ - <未解析的重载函数类型> 尝试将聚合对象的方法传递给其类方法时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7015362/