The problem is because you did not implement a
copy assignment operator as I instructed you, so when "ab" (line 109) is destructed (line 125), it destroys "mxAB"'s memory too...
To see the difference, change lines 165 and 166 to:
165 166
|
Array2D mxAB(mxA3.multiplyMatrix(mxB3));
|
In this case, you have a proper
copy constructor implemented, so when "ab" (line 109) is destructed, it only affects itself (since "mxAB" has its
own copy of the matrix data).
A few other things you should be aware of:
Line 33:
static int size=0;
What is this for?
Line 36: Your default constructor
needs to initialize the values of your class, otherwise your destructor will crash your program with a GPF.
34 35 36 37 38
|
Array2D::Array2D()
{
row = col = 0;
m = NULL;
}
|
Now, when your destructor is called, make sure you don't try to
delete[] anything that doesn't exist:
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|
Array2D::~Array2D()
{
if (m != NULL)
{
for (int i = 0; i < row; i++)
{
delete[]m[i];
}
delete[]m;
}
// This isn't actually necessary in the destructor, but keep reading...
row = col = 0;
m = NULL;
}
|
When you implement your assignment operator, keep in mind that you may have to destroy existing data:
1 2 3 4 5 6 7 8 9
|
Array2D& Array2D::operator = ( const Array2D& a )
{
if (m != NULL)
{
finalize(); // same stuff as in destructor, not forgetting the stuff = 0 statements
}
copy( a ); // same stuff as in the copy constructor
}
|
[edit] You will need to implement the
finalize() and
copy() methods, just like
initialize() and
generateArray2D() are.[/edit]
Finally, your matrix class does not make its size or contents available for inspection. You might want to add that kind of stuff:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
class Array2D
{
public:
...
int rows() const { return row; }
int columns() const { return col; }
int& index( int r, int c ) { return m[r][c]; }
...
};
...
int main()
{
...
cout << "The size of matrix A is " << mxA3.rows() << " by " << mxA3.columns() << ".\n";
...
mxA3.index( 0, 1 ) = 42;
...
|
Hope this helps.