#ifndef _VECTOR_H_
#define _VECTOR_H_
template <class T>
class Vector {
private:
int nn; // size of array. upper index is nn-1
T *v;
public:
Vector(int n, const T &a); //initialize to constant value
~Vector();
};
#endif
Vector.cc
1 2 3 4 5 6 7 8 9 10 11 12
#include <iomanip>
#include "Vector.h"
template <class T>
Vector<T>::Vector(int n, const T& a) : nn(n), v(n>0 ? new T[n] : NULL) {
for(int i=0; i<n; i++) v[i] = a;
}
template <class T>
Vector<T>::~Vector() {
if (v != NULL) delete[] (v);
}
I compiled it with g++ in linux as follows.
g++ main.cc Vector.cc -o main
Here's the output.
main.cc:(.text+0x2c): undefined reference to `Vector<double>::Vector(int, double const&)'
main.cc:(.text+0x3d): undefined reference to `Vector<double>::~Vector()'
collect2: ld returned 1 exit status
Template functions have to be defined in the same same file as they are declared or they'll produce linker errors. Alternatively, if your compiler supports the export keyword (and it almost certainly doesn't), you can use it to put the definition in a different file.
If one day you're bored out of your mind, open the standard <vector> header. You'll notice that includes the entire definition of the std::vector class.