hello, this is my first post so forgive me if i did anything wrong.
so i tried to create a simple templated class to store a 2d dynamic array. all the code is good when its stored in the same file but i wanted to try using class declarations and definitions via header and .cpp files. to my dismay my compiler gave me an error: LNK2019 unresolved external symbol. i have no clue what that means as im fairly new to C++ but the error goes away when i use #include "Matrix.cpp" instead of #include "Matrix.h". this is not the way i was taught to use header files so im wondering what i am doing wrong. im using microsoft visual c++. any help is appreciated and thx in advance. here is my code:
#ifndef MATRIX_H
#define MATRIX_H
template <typename T>
class Matrix
{
private:
int mGridWidth;
int mGridHeight;
T *mGrid;
Matrix();
public:
Matrix(int gridWidth, int gridHeight);
~Matrix(void);
T& operator ()(int column, int row);
int GetWidth();
int GetHeight();
};
#endif
#include "Matrix.h"
//#include "Matrix.cpp" //use this and the error goes away
#include <iostream>
int main()
{
usingnamespace std;
Matrix<double> Foo(8,8); //this throws the first error
Foo(4,3) = 9;
cout << Foo(4,3) << endl;
cout << "Press Enter to continue...";
cin.get();
return 0;
}
this is the exact error of the first LNK2019 error, there are actually 3 of them
error LNK2019: unresolved external symbol "public: double & __thiscall Matrix<double>::operator()(int,int)" (??R?$Matrix@N@@QAEAANHH@Z) referenced in function _main
i hope thats all the information necessary, if not just ask
It's the correct way for templates and inline functions. For non-inline, non-templated functions, you'd put them in a cpp file like you originally tried. Templates are just weird like that.
It doesn't matter whether your put them in the class or afterward. Whichever you prefer.