【发布时间】:2011-10-24 07:52:34
【问题描述】:
我在编译我的代码时遇到了一些问题。 我有以下结构:
#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声明为成员函数。如果你把它设为static类函数,它应该可以工作。当然,如果它引用它就行不通,你需要一种不同的方法。 -
用最小的程序重现问题,然后贴出完整的真实代码。
-
class MyClass中没有成员函数void run()。此外,AnotherClass将在MyClass之前定义(或至少向前声明)
标签: c++ function pointers call aggregation