#include "grid.h"
template <typename T>
Grid<T>::Grid(int inWidth, int inHeight) : mWidth(inWidth), mHeight(inHeight)
{
mCells = new T* [mWidth];
for (int i = 0; i < mWidth; i++) {
mCells[i] = new T[mHeight];
}
}
template <typename T>
constint Grid<T>::kDefaultWidth;
template <typename T>
constint Grid<T>::kDefaultHeight;
template <typename T>
Grid<T>::Grid(const Grid<T>& src)
{
copyFrom(src);
}
template <typename T>
Grid<T>::~Grid()
{
freeMemory();
}
template <typename T>
Grid<T>& Grid<T>::operator=(const Grid<T>& rhs)
{
if (this == &rhs) {
return (*this);
}
freeMemory();
copyFrom(rhs);
return (*this);
}
template <typename T>
void Grid<T>::setElementAt(int x, int y, const T& element)
{
mCells[x][y] = element;
}
template <typename T>
T& Grid<T>::getElementAt(int x, int y)
{
return (mCells[x][y]);
}
template <typename T>
const T& Grid<T>::getElementAt(int x, int y) const
{
return (mCells[x][y]);
}
template <typename T>
void Grid<T>::copyFrom(const Grid<T>& src)
{
mWidth = src.mWidth;
mHeight = src.mHeight;
mCells = new T* [mWidth];
for (int i = 0; i < mWidth; i++) {
mCells[i] = new T[mHeight];
}
for (int i = 0; i < mWidth; i++) {
for(int j = 0; j < mHeight; j++) {
mCells[i][j] = src.mCells[i][j];
}
}
}
template <typename T>
void Grid<T>::freeMemory()
{
for(int i = 0; i < mWidth; i++)
{
delete [] mCells[i];
}
}
and this in 'main.cpp':
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
#include "grid.h"
int main(int argc, char** argv)
{
Grid<int> myIntGrid(10,10);
myIntGrid.setElementAt(0, 0, 10);
int x = myIntGrid.getElementAt(0, 0);
return (0);
}
OK. Here's the structure:
Grid.h is included by Grid.cpp (its definition) and Main.cpp (a 'test' method).
But when I compile, I receive the following list of errors:
1 2 3 4 5 6 7 8 9
C:\Users\...\Projects\C-C++\Sample\main.cpp||In function `int main(int, char**)':|
C:\Users\...\Projects\C-C++\Sample\main.cpp|9|warning: unused variable 'x'|
obj\Debug\main.o||In function `main':|
C:\Users\...\Projects\C-C++\Sample\main.cpp|7|undefined reference to `Grid<int>::Grid(int, int)'|
C:\Users\...\Projects\C-C++\Sample\main.cpp|8|undefined reference to `Grid<int>::setElementAt(int, int, int const&)'|
C:\Users\...\Projects\C-C++\Sample\main.cpp|9|undefined reference to `Grid<int>::getElementAt(int, int)'|
C:\Users\...\Projects\C-C++\Sample\main.cpp|11|undefined reference to `Grid<int>::~Grid()'|
C:\Users\...\Projects\C-C++\Sample\main.cpp|11|undefined reference to `Grid<int>::~Grid()'|
||=== Build finished: 5 errors, 1 warnings ===|
But if I append the content of 'grid.cpp' (the implementation) to 'grid.h' (the declaration), it compiles without error.
And the other strange thing is that when I include the file grid.cpp in the main.cpp, the compilation is successfull!
Please help me.