I'm new to making my own template classes in C++, and after several hours of searching online for answers and toying with the function & its parameters, I've given up. I'm having run-time trouble with the following class' "=" operator:
In matrix.h:
template <class datatype> class Matrix{
datatype** element;
unsigned int m,n;
public:
Matrix(unsigned int M, unsigned int N,datatype x){
m=M; // # of rows
n=N; // # of cols
element=new datatype*[m];
for(int i=0;i<m;i++) element[i]=new datatype[n];
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
element[i][j]=x;
}
void print(){
for(int i=0;i<m;i++){
for(int j=0;j<n;j++) cout<<element[i][j]<<" ";
cout<<"\n";
}
}
Matrix operator=(Matrix A){
for(int i=0;i<m;i++) delete[] element[i];
delete[] element;
m=A.m;
n=A.n;
element=new datatype*[m];
for(int i=0;i<m;i++) element[i]=new datatype[n];
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
element[i][j]=A.element[i][j];
return *this;
}
};
When I go to test this, compilation & linking run smoothly w/o error, and I get a perfectly valid print. But when trying to assign one matrix to the value of another, the program crashes w/ message "matrix_test has stopped working". Here's my testing code, in matrix_test.cpp:
Matrix<int> M(5u,3u,0);
Matrix<int> P(2u,7u,3);
int main(){
M.print();
cout<<"\n";
P.print();
cout<<"\n";
P=M;
P.print();
}
Thanks in advance for the help!