2017-07-12 37 views
-1
#include <iostream> 

    struct A { 
     explicit A(int a) : _a(a) {}; 
     int _a; 
    }; 

    struct ClassFunction { 
     ClassFunction(std::shared_ptr<A> myA) : _myA(myA) {} 

     double operator() (int &x, 
          int &g) { 
      return 1.0 
        + static_cast<double>(_myA->_a); // offending line 
     } 
     static double wrap(int x, int g, void *data) { 
      return (*reinterpret_cast<ClassFunction*>(data)) (x,g); 
     } 
     std::shared_ptr<A> _myA; 
    }; 

    int main() { 
     int x = 1; 
     int g; 
     auto myA = std::shared_ptr<A>(new A(int(20))); 
     ClassFunction myClassFunction(myA); 
     std::cout << ClassFunction::wrap(x,g,NULL) << std::endl; 
     return 0; 
    } 

我试图创建一个功能对象类ClassFunction采用一个std::shared_ptr<A>作为参数,这是我然后经由static成员函数调用ClassFunction::wrap的参数。访问通过一个C++函数对象类

如果我访问A的数据成员为myA->_a该程序无法运行(但它的编译没有任何抱怨,但是)。

我该如何做这项工作?

+0

你通过不传递一个空指针来'wrap'工作吗? –

+3

你为什么写'ClassFunction :: wrap(x,g,NULL)',你打算在这里提供一个空指针?你为什么期望工作? – Angew

+0

它与优化库NLOPT提供的样板代码非常相似,如果函数类是MyFunction,那么你可以定义一个静态成员函数:“static double wrap (const std :: vector &x,std :: vector &grad,void * data){ return(* reinterpret_cast (data))(x,grad); }' –

回答

1

尝试以下方法:

的reinterpret_cast < ClassFunction *>(数据)可适用于当数据点,以ClassFunction类的实例。

+0

是的,这是我没有抓住。谢谢! –