If I do not use the destructor, then everything works fine, but when I add it, the following error occurs:
Exception thrown at 0x00742BAF in Bitwise.exe: 0xC0000005: Access violation reading location 0xDDDDDDDD.
Can anyone tell me what is happening and how I might be able to fix this problem?
Here is the code that is causing the problem:
typedef double *arr;
class twod {
arr *ar;
int row;
int collum;
public:
twod() {
row = 3;
collum = 3;
ar = new arr[row];
for (int i = 0; i < row; i++) {
ar[i] = new double[collum];
}
}
void setel() {
for (int i = 0; i < row; i++) {
for (int j = 0; j < collum; j++) {
cin >> ar[i][j];
}
}
}
twod(int a, int b) {
row = a;
collum = b;
ar = new arr[row];
for (int i = 0; i < row; i++) {
ar[i] = new double[collum];
}
}
twod operator=(const twod &a) {
if (this != &a) {
for (int i = 0; i < row; i++) {
delete[] ar[i];
}
delete[] ar;
row = a.row;
collum = a.collum;
ar = new arr[row];
for (int i = 0; i < row; i++) {
ar[i] = new double[collum];
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < collum; j++) {
ar[i][j] = a.ar[i][j];
}
}
}
return *this;
}
void out() {
for (int i = 0; i < row; i++) {
for (int j = 0; j < collum; j++) {
cout << this->ar[i][j];
}
cout << endl;
}
}
friend twod operator+(const twod &a, const twod &b);
~twod() {
for (int i = 0; i < this->row; i++) {
delete[] this->ar[i];
}
delete[] this->ar;
}
};
twod operator+(const twod &a, const twod &b) {
if (a.collum != b.collum || a.row != b.row) {
cout << "cant" << endl;
exit(0);
} else {
twod d(a.row, a.collum);
for (int i = 0; i < d.row; i++) {
for (int j = 0; j < d.collum; j++) {
d.ar[i][j] = a.ar[i][j] + b.ar[i][j];
}
}
return d;
}
}
int main() {
twod a(3, 3), b(3, 3), c;
a.setel();
a.out();
b.setel();
b.out();
c = (a + b);
c.out();
}
User contributions licensed under CC BY-SA 3.0