I have a class representing a three dimensional matrix of integers in which I am trying to implement the operator+ for addition of an integer to all elements of the matrix. The class signature looks like this,
Expand|Select|Wrap|Line Numbers
- class Matrix
- {
- public:
- Matrix();
- Matrix(const Matrix& _object);
- Matrix(const unsigned int _iMax, const unsigned int _jMax, const unsigned int _kMax);
- ~Matrix();
- Matrix& operator=(const Matrix& rhs);
- Matrix& operator=(const int& rhs);
- Matrix operator+(const int& rhs) const;
- };
Expand|Select|Wrap|Line Numbers
- int main(int argc, char* argv[])
- {
- Matrix mat(5, 5, 5);
- mat = 0;
- Matrix mat3;
- mat3 = mat + 1;
- return 0;
- }
On a whim, I added the copy constructor to see if the behavior was different. Sure enough, when I define the copy constructor the compiler is converting the line,
Expand|Select|Wrap|Line Numbers
- mat3 = mat + 1
Expand|Select|Wrap|Line Numbers
- mat3.operator=(new Matrix(mat.operator+(1)))
What I am wondering is if this should be required, or if I have a problem in the implementation of my + and = operators. I really dislike having yet another class instantiation and copy here since the internal matrix could be big. Hate to use the memory as well as have to copy the data.
My operators + and = are implemented as shown below,
Expand|Select|Wrap|Line Numbers
- Matrix& Matrix::operator=(const Matrix& rhs)
- {
- iMax = rhs.iMax;
- jMax = rhs.jMax;
- kMax = rhs.kMax;
- if (data!= 0)
- {
- delete [] data;
- }
- data = new int[iMax * jMax * kMax];
- for (unsigned int ijk = 0; ijk < iMax * jMax * kMax; ijk++)
- {
- data[ijk] = rhs.data[ijk];
- }
- return *this;
- }
- Matrix Matrix::operator+(const int& rhs) const
- {
- Matrix newMat(iMax, jMax, kMax);
- for (unsigned int ijk = 0; ijk < iMax * jMax * kMax; ijk++)
- {
- newMat.data[ijk] = data[ijk] + rhs;
- }
- return newMat;
- }