-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); }' –