可能重复:
Undefined reference error for template method
Splitting templated C++ classes into .hpp/.cpp files--is it possible?
我有这堂课:
matrix.h
#ifndef MATRIX_H
#define MATRIX_H
#include <vector>
#include <iostream>
using namespace std;
template <class T> class matrix;
template <typename T> ostream& operator<< (ostream& o, const matrix<T>& m);
template <class T>
class matrix
{
public:
matrix(const int&);
void push(const T&);
void setRows(const int&);
int size();
T& operator ()(const int&, const int&);
friend ostream& operator<< <>(ostream&, const matrix<T>&);
virtual ~matrix();
private:
vector<T> elements_;
int dimension_;
};
#endif // MATRIX_H
#include "matrix.h"
#include <vector>
matrix.cpp
template <class T>
matrix<T>::matrix(const int& n)
{
dimension_ = n;
}
template <class T>
void matrix<T>::push(const T& element)
{
elements_.resize( elements_.size() + 1, element);
}
template <class T>
int matrix<T>::size()
{
return elements_.size()/dimension_;
}
template <class T>
T& matrix<T>::operator ()(const int &n, const int &m)
{
if ((n < 0) || (n > dimension_))
{
cerr << "Row index out of range"
<< endl << endl;
}
if ((m < 0) || (m > dimension_))
{
cerr << "Column index out of range"
<< endl << endl;
}
return elements_[n*dimension_+m];
}
template <class T>
ostream& operator << (ostream& o, const matrix<T>& m)
{
for (int i = 0; i < m.size(); i++)
{
for (int j = 0; j < m.size(); i++)
{
o << m(i,j) << " ";
}
o << endl;
}
return o;
}
template <class T>
matrix<T>::~matrix()
{
//dtor
}
And this program:
#include "matrix.h"
#include <iostream>
using namespace std;
int main()
{
matrix<int> m(3);
m.push(10);
m.push(10);
m.push(11);
m.push(11);
m.push(12);
m.push(12);
m.push(13);
m.push(13);
m.push(10);
cout << m;
cout << "Hello world!" << endl;
return 0;
}
对于每一个。单。一。在我调用的方法中,我得到一个像这样的编译器错误:
C:\ Users ... \ main.cpp | 8 |未定义引用 `matrix :: matrix(int const&amp;)'|
我已经构建了matrix.cpp文件。我正在使用Code :: Blocks,所以我在obj文件夹中有一个matrix.o文件。那不是问题。
这是什么?