Simple operator overloading issue
Hey guys. Still working on that matrix class. I thought I'd have no problems making something as simple as scalar * matrix but it appears I'm wrong. I create an identity matrix 5x5 and simply multiply it by the scalar 2. I then assign the result to another matrix and output the new matrix. The new matrix has only zeros but it should be a diagonal matrix with only 2's... Here's the relevant code:
Code:
template < class T >
Matrix< T >::Matrix< T >(const Matrix& m)
{
*this = m;
}
template < class T >
Matrix< T > Matrix< T >::IdentityMatrix(unsigned int size)
{
Matrix< T > tmp(size, size);
for(int j = 0; j < tmp.Rows; j++)
{
for(int i = 0; i < tmp.Cols; i++)
{
tmp.Data[j][i] = i == j ? 1 : 0;
}
}
return tmp;
}
template < class T >
Matrix< T >& Matrix< T >::operator = (const Matrix< T >& m)
{
Rows = m.Rows;
Cols = m.Cols;
Data.assign(m.Data.begin(), m.Data.end());
return *this;
}
template < class T >
Matrix< T > Matrix< T >::operator * (const T& val) const
{
Matrix< T > tmp(Cols, Rows);
if(Rows > 0 && Cols > 0)
{
for(int j = 0; j < Rows; j++)
{
for(int i = 0; i < Cols; i++)
{
tmp.Data[j][i] *= val;
}
}
}
return tmp;
}
// this is the problematic code
int main()
{
Matrix<float> m = Matrix<float>::IdentityMatrix(5);
Matrix<float> m2 = m * 2;
m2.Output( );
}
What's really bugging me is that I know for sure that the first three are correct because I have already tested them. It leaves me with the last function which seems correct to me. Does anyone have an idea ?