C++ 通过C+访问参数+;函数对象类 #包括 结构A{ 显式A(inta):_A(A){}; 国际组织; }; 结构类函数{ 类函数(std::shared_ptr myA):_myA(myA){ 双运算符()(int&x, (国际和全球){ 返回1.0 +静态_cast(_myA->_a);//不符合要求的行 } 静态双换行(int x、int g、void*数据){ 返回(*重新解释铸件(数据))(x,g); } std::共享ptr myA; }; int main(){ int x=1; int g; 自动myA=std::shared_ptr(新的A(int(20)); 类函数myClassFunction(myA); std::cout

C++ 通过C+访问参数+;函数对象类 #包括 结构A{ 显式A(inta):_A(A){}; 国际组织; }; 结构类函数{ 类函数(std::shared_ptr myA):_myA(myA){ 双运算符()(int&x, (国际和全球){ 返回1.0 +静态_cast(_myA->_a);//不符合要求的行 } 静态双换行(int x、int g、void*数据){ 返回(*重新解释铸件(数据))(x,g); } std::共享ptr myA; }; int main(){ int x=1; int g; 自动myA=std::shared_ptr(新的A(int(20)); 类函数myClassFunction(myA); std::cout,c++,c++11,C++,C++11,尝试以下操作: #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,

尝试以下操作:

    #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;
    }

std::不向
wrap
传递一个空指针能让它工作吗?为什么要编写
ClassFunction::wrap(x,g,null)
以及在这里提供一个空指针的目的是什么?为什么希望它工作?它与优化库
NLOPT
建议的样板代码非常相似,“…使用两行辅助函数。如果您的函数类是MyFunction,则可以定义静态成员函数:”
static double wrap(const std::vector&x,std::vector&grad,void*data){return(*reinterpret_cast(data))(x,grad);}
我完全不知道整个混乱的目的是什么。为什么要使用静态函数调用您创建的函数对象?您传递的是空指针,因此静态调用访问空内存位置,就这么简单。它甚至不会到达
操作符()
code,它应该在
data
的解引用处失败。你知道
wrap
的代码是做什么的吗?它对
data
参数做了什么?同样,你希望通过在那里传递空指针得到什么?是的,这是我没有掌握的。谢谢!
std::cout << ClassFunction::wrap(x, g, &myClassFunction) << std::endl;