C ++类表达式参数定义不正确

时间:2013-03-17 20:09:48

标签: c++ c++11 undefined-reference

我正在学习C ++,目前遇到类模板的奇怪问题。 这是我的头文件:

#ifndef VECTOR_H
#define VECTOR_H
#include <iostream>
#include <list>

using namespace std;

template <int n>
class Vector {

public:
    list<float> coords;
    Vector();
    Vector(list<float> ncoords);
};

template <int n>
Vector<n>::Vector() {
    coords.assign(n, 0.0);
}
#endif

这是我的.cpp文件:

#include "vector.h"
#include <list>

using std::ostream;
using namespace std;

template <int n>
Vector<n>::Vector(list<float> ncoords): coords {ncoords}{}

如果我Vector<2> vector;

,一切正常

但是如果我尝试,链接器会出错 Vector<20> vector2 { list<float>{} };

错误消息

  

未定义引用`Vector&lt; 20&gt; :: Vector(std :: list&gt;)'

问题是 - 我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

模板必须在头文件中实现。这是由于链接工作的方式。仔细阅读详尽的答案here。并在下次询问之前进行搜索。