I am quite new to C++. My problem is to write an OOP C++ program about matrix (create a matrix class and add some methods to this class) Here is my code:
#include <iostream>
#include <iomanip>
using namespace std;
class Matrix
{
private:
int col, row;
double *a;
public:
Matrix(int col = 1, int row = 1) {
this->col = col; this->row = row;
}
~Matrix() {
delete a;
col = row = 0;
}
void insertMatrix() {
a = new double[this->col * this->row];
for (int i = 0; i < this->row; i++)
for (int j = 0; j < this->col; j++) {
cout << endl << "a[" << i + 1 << "][" << j + 1 << "] = ";
cin >> this->a[i * this->col + j];
}
}
void printMatrix() {
for (int i = 0; i < this->row; i++) {
for (int j = 0; j < this->col; j++)
cout << setw(9) << this->a[i * this->col + j];
cout << endl;
}
cout << endl;
}
int getCol() {
return col;
}
int getRow() {
return row;
}
Matrix operator+(Matrix);
Matrix operator-(Matrix);
};
Matrix Matrix::operator+(Matrix x) {
if (x.col != col || x.row != row) {
cout << endl << "Can't add these two matrices";
exit(0);
}
Matrix sum(x.col, x.row);
sum.a = new double(sum.col * sum.row);
for (int i = 0; i < this->col * this->row; i++)
sum.a[i] = a[i] + x.a[i];
return sum;
}
Matrix Matrix::operator-(Matrix x) {
if (x.col != this->col || x.row != this->row) {
cout << endl << "Can't subtract these two matrices";
exit(0);
}
Matrix dif(this->col, this->row);
dif.a = new double(dif.col * dif.row);
for (int i = 0; i < this->col * this->row; i++)
dif.a[i] = this->a[i] - x.a[i];
return dif;
}
int main()
{
int row, col;
cout << endl << "Column = "; cin >> col; cout << endl << "Row = "; cin >> row;
Matrix A(col, row), B(col, row);
A.insertMatrix(); B.insertMatrix();
cout << "Matrix A: " << endl; A.printMatrix();
cout << "Matrix B: " << endl; B.printMatrix();
cout << "Matrix (A + B)" << endl; (A + B).printMatrix();
cout << "Matrix (A - B)" << endl; (A - B).printMatrix();
}
I don't see any mistake at all. I can compile the program. But every time I try to input some numbers, the program keeps freezing with the message "stop working" and gets the wrong answer. I use Orwell Dev C++ in Windows 8. Can anyone explain why?