Reputation: 9
I am writing some code using template,but i got some link errors:
[Linker error] undefined reference to `Vector::Vector(Vector const&)'
But i wrote this function in a .cpp.Here is the code.
template <class T>
Vector<T>::Vector(Vector const& r)
{
m_nSize = r.size();
int i = 0;
m_pElements = new T[m_nSize];
while(i <= m_nSize)
{
m_pElements[i] = r[i];
i++;
}
}
and it is declared here in .h:
template <class T>
class Vector
{
public:
Vector():m_nSize(0){ m_pElements = (T*)NULL; }
Vector(int size):m_nSize(size){ m_pElements = new T[size]; }
Vector(const Vector& r);
virtual ~Vector(){ delete m_pElements; }
T& operator[](int index){ return m_pElements[index];}
int size(){return m_nSize;}
int inflate(int addSize);
private:
T *m_pElements;
int m_nSize;
};
I'm really confused now...What should i do to correct is?
Upvotes: 0
Views: 90
Reputation: 12254
See the C++ faq (http://www.parashift.com/c++-faq-lite/templates.html#faq-35.13). Basically place the code in the header file.
Upvotes: 2
Reputation: 258678
You should make implementations visible. Move
template <class T>
Vector<T>::Vector(Vector const& r)
{
//....
}
from the cpp
file to the header.
Upvotes: 3