-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
該程序無法運行(但它的編譯沒有任何抱怨,但是)。
我該如何做這項工作?
你通過不傳遞一個空指針來'wrap'工作嗎? –
你爲什麼寫'ClassFunction :: wrap(x,g,NULL)',你打算在這裏提供一個空指針?你爲什麼期望工作? – Angew
它與優化庫NLOPT提供的樣板代碼非常相似,如果函數類是MyFunction,那麼你可以定義一個靜態成員函數:「static double wrap (const std :: vector&x,std :: vector &grad,void * data){ return(* reinterpret_cast (data))(x,grad); }' –