ploblem with operator

I don't know what's wrong with it!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <iostream>
using namespace std;
class Matrix{
public:
int m,n;
int *data;
Matrix(int h=1,int w=1){data=new int[(m=h)*(n=w)];}
~Matrix(){delete[]data;}
void print();
int &operator[](int i);
int &operator()(int r,int c);
void operator=(Matrix);
};
////////////////////////////////////////
int &Matrix::operator ()(int r, int c)
{
return data[r*n+c];
}
////////////////////////////////////////
int &Matrix::operator[](int i)
{
return data[i];
}
///////////////////////////////////////
void Matrix::operator=(Matrix A)
{

for(int i=0;i<m*n;i++)
{
(*this)[i]=A[i];
/*cout<<(this)->data[i]<<" "<<A[i]<<endl;*/
//It seems there is no problem!

}

}
///////////////////////////////////////
void Matrix::print()
{
int i,j;
for(i=0;i<m;i++,cout<<endl)
for(j=0;j<n;j++)
cout<<(*this)(i,j)<<" ";
}
////////////////////////////////////////
int main()
{
int i,m,s,t;
Matrix B(3,3),C(3,3),D(3,3);

for(i=0;i<9;i++)
C[i]=5;
cout<<endl<<"C="<<endl;
C.print();
for(i=0;i<9;i++)
B[i]=i;
cout<<endl<<"B="<<endl;
B.print();

B=C;
cout<<endl<<"after!"<<endl<<"B="<<endl;
B.print();
cout<<endl<<"C="<<endl;
C.print();


system ("pause");
return 0;}

You have not defined the copy constructor and the default one doesn't do what you want. In your code the copy constructor is used to construct A in operator= from C in main when using operator= on line 60.

You could make A a reference and no copy has to be made
void Matrix::operator=(const Matrix& A)
but you probably still want to define a copy constructor. See the rule of 3 http://en.wikipedia.org/wiki/Rule_of_three_%28C%2B%2B_programming%29
You know what you did wrong?
This line:

void Matrix::operator=(Matrix A)
A Matrix gets copied, but you have no correct copy constructor.
You can fix it like this:
1
2
3
4
5
6
7
void Matrix::operator=(const Matrix& A)
// Also remember this line:
void operator=(const Matrix&);
// You also need to make a constant version for:
int &operator[](int i);
// Like:
const int& operator[](int i) const;


+1 Peter87, Didn't reload the page while doing the test and found out your answer after I posted mine.
Last edited on
Topic archived. No new replies allowed.