c++ - <未解析的重载函数类型> 尝试将聚合对象的方法传递给其类方法时

标签 c++ function pointers call aggregation

我在编译代码时遇到一些问题。 我有以下结构:

#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/

相关文章:

c++ - 预处理器宏扩展到另一个预处理器指令

c++ - ‘ptr_fun(isalnum)’ 不能在 g++ 中编译?

c++ - SDL - 像控制台一样打印文本?

r - 在不附加包的情况下评估包环境中的功能

Javascript 函数声明。什么时候用什么?

c++ - 使用指向派生类的指针作为模板参数时出错

pointers - 如何跨包中的文件使用全局变量?

c++ - 为并发运行时实现任务局部变量

c - findAndReplace函数的实现

c - 程序不会打印矩阵