0

このコードをコンパイルしようとしましたが、苦情はありません。ただし、実行すると、最後の行で例外エラーが発生します。つまり、 cout<<"Norm:"<

この問題を解決する方法を教えてください。前もって感謝します

#include <stdafx.h>
#include <iostream>
#include <string>
#include <boost/function.hpp>
#include <boost/array.hpp>

using namespace std;

template<typename R,typename D> 
class GenericFunction
{
private:
    boost::function<R (D)> f;
protected:
    GenericFunction(){};
public:
    GenericFunction(const boost::function<R (D)>& myFunction){f=myFunction;};
    R evaluate(const D& value) const{cout<<"Good Job"<<endl;} ;
    R operator ()(const D& value);// const{ return f(value); };
}; 
template <typename R, typename D, int N>
class ScalarValuedFunction:public GenericFunction<R,boost::array<D, N>>
{
public:
    ScalarValuedFunction(const boost::function<R (const boost::array<D, N>)> &myF){};
};


template<typename Numeric, std::size_t N>
Numeric Norm(const boost::array<Numeric , N>& Vec)
{
    Numeric Result=Vec[0]*Vec[0];
    for (std::size_t i=1; i<Vec.size();i++)
    {
        Result+=Vec[i]*Vec[i];
    }
    return Result;
} 

double test(double t)
{
    return t;
}

int main ()
{
    const int N=4;
    boost::array<double, N> arr={0.2,  .3,  1.1,  4};
    ScalarValuedFunction<double, double, N> myfun(Norm<double,N>);  

    cout<<"Norm:"<<myfun(arr)<<endl;
}
4

1 に答える 1

3

関数の引数を基本クラスのコンストラクターに転送していません。

ScalarValuedFunction(const boost::function<R (const boost::array<D, N>)> &myF)
    : GenericFunction<R, boost::array<D, N>>(myF) // <=== ADD THIS
{
} //; <== SEMICOLON NOT NEEDED AFTER A FUNCTION DEFINITION!

これを行わないと、GenericFunctionサブオブジェクトは既定のコンストラクター ( として宣言されているため、派生クラスからアクセス可能protected) に初期化され、そのメンバー変数fも既定で初期化されます。

次に、内部でそれを呼び出そうとするとoperator ()(その定義はコメントで示したものだと思います)、Ka-Boom.

于 2013-02-21T20:30:32.117 に答える