【问题标题】:fatal error LNK1120: 1 unresolved externals致命错误 LNK1120:1 个未解决的外部问题
【发布时间】:2013-02-21 01:54:44
【问题描述】:

我正在编译以下代码,但收到错误消息。我想在boost中练习模板,我不知道如何处理这个问题

#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);
    R evaluate(const D& value) const ;
    R operator ()(const D& value) const;
};
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;
}

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

并收到以下错误,

ConsoleApplication2.obj : error LNK2019: unresolved external symbol "public: __thiscall ScalarValuedFunction<double,double,4>::ScalarValuedFunction<double,double,4>(class boost::function<double __cdecl(class boost::array<double,4>)> const &)" (??0?$ScalarValuedFunction@NN$03@@QAE@ABV?$function@$$A6ANV?$array@N$03@boost@@@Z@boost@@@Z) referenced in function _main
1>c:\users\university\documents\visual studio 2012\Projects\ConsoleApplication2\Debug\ConsoleApplication2.exe : fatal error LNK1120: 1 unresolved externals

请有人告诉我我的代码有什么问题?

【问题讨论】:

  • 您为ScalarValuedFunction&lt;&gt; 声明了一个构造函数,但没有定义它。当然,一旦你这样做了,你还需要为 GenericFunction&lt;&gt; 定义构造函数。

标签: c++ templates


【解决方案1】:

您没有为ScalarValuedFunction 类模板的构造函数提供定义,但在类模板的定义中声明了

ScalarValuedFunction(const boost::function<R (const boost::array<D, N>)> &myF);

因此,链接器抱怨无法解析对构造函数的调用。调用发生在main():

ScalarValuedFunction<double, double, N> myfun(Norm<double,N>);

要解决您的问题,请为构造函数添加一个定义。例如:

template<typename R, typename D, int N>
ScalarValuedFunction<R, D, N:::ScalarValuedFunction(
    const boost::function<R (const boost::array<D, N>)> &myF
    )
    :
    GenericFunction<R, boost::array<D, N>>::GenericFunction(myMF)
{ }

【讨论】:

  • 谢谢,这解释了很多
  • @user2085646:很高兴它有帮助
【解决方案2】:

您还没有为ScalarValuedFunction 类定义构造函数,只是声明了它。

【讨论】:

    猜你喜欢
    • 2011-11-16
    • 1970-01-01
    • 2013-07-10
    • 2012-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-25
    相关资源
    最近更新 更多