I'm new to class templates (templates in general, actually) and I'm trying to figure out why this won't compile.
Code:
// MATRIX.h
#ifndef MATRIX_H
#define MATRIX_H
template <typename T>
class Matrix {
public:
Matrix(int rows, int cols);
Matrix(const Matrix &other);
virtual ~Matrix();
Matrix& operator=(const Matrix &rhs);
T* operator[](int i);
int getRows() const;
int getCols() const;
protected:
void copy(const Matrix &other);
private:
Matrix();
int m_rows;
int m_cols;
T *m_linArray;
};
#include "MATRIX.cpp"
#endif /* MATRIX_H */
Code:
// MATRIX.cpp
#include "MATRIX.h"
template <typename T>
Matrix<T>::Matrix()
{}
template <typename T>
Matrix<T>::Matrix(int rows, int cols) {
m_rows = rows;
m_cols = cols;
m_linArray = new T[m_rows * m_cols];
}
template <typename T>
Matrix<T>::Matrix(const Matrix &other) {
copy(other);
}
template <typename T>
Matrix<T>::~Matrix() {
delete[] m_linArray;
}
template <typename T>
Matrix<T>&
Matrix<T>::operator=(const Matrix &other) {
if( this != &other ) {
delete[] m_linArray;
copy(other);
}
return *this;
}
template <typename T>
T* Matrix<T>::operator[](int i) {
return m_linArray + (i*m_cols);
}
template <typename T>
void
Matrix<T>::copy(const Matrix &other) {
m_rows = other.m_rows;
m_cols = other.m_cols;
int size = m_rows * m_cols;
m_linArray = new T[size];
for( int i=0; i < size; i++ ) {
m_linArray[i] =
other.m_linArray[i];
}
}
template <typename T>
int Matrix<T>::getRows() const {
return m_rows;
}
template <typename T>
int Matrix<T>::getCols() const {
return m_cols;
}
I'm getting the following errors:
.\TEMP.cpp(4) : error C2143: syntax error : missing ';' before '<'
1>.\TEMP.cpp(4) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>.\TEMP.cpp(4) : error C2988: unrecognizable template declaration/definition
1>.\TEMP.cpp(4) : error C2059: syntax error : '<'
1>.\TEMP.cpp(8) : error C2143: syntax error : missing ';' before '{'
1>.\TEMP.cpp(8) : error C2447: '{' : missing function header (old-style formal list?)
1>.\TEMP.cpp(15) : error C2143: syntax error : missing ';' before '<'
1>.\TEMP.cpp(15) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>.\TEMP.cpp(15) : error C2086: 'int Matrix' : redefinition
1> .\TEMP.cpp(4) : see declaration of 'Matrix'
1>.\TEMP.cpp(15) : error C2988: unrecognizable template declaration/definition
1>.\TEMP.cpp(15) : error C2059: syntax error : '<'
1>.\TEMP.cpp(20) : error C2588: '::~Matrix' : illegal global destructor
1>.\TEMP.cpp(20) : fatal error C1903: unable to recover from previous error(s); stopping compilation
Is there something wrong with the syntax? Or perhaps I'm not including something I need to include? I've tried compiling this with both Visual C++ and g++ to no avail. Any help would be appreciated.