2017-07-12 38 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

是的,這是我沒有抓住。謝謝! –