【发布时间】:2015-01-04 19:44:25
【问题描述】:
我对 C++ 很陌生。 我的问题是编写一个关于矩阵的 OOP C++ 程序(创建一个矩阵类并在这个类中添加一些方法) 这是我的代码:
#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();
}
我看不出有任何错误。我可以编译程序。但是每次我尝试输入一些数字时,程序都会冻结并显示“停止工作”的消息并得到错误的答案。 我在 Windows 8 中使用 Orwell Dev C++。 谁能解释一下为什么?
【问题讨论】:
-
这有点难说;您可以使用调试器或提供表现相同行为的程序的一小部分吗?
-
好吧,实际上我尝试调试但我找不到错误。我相信 printMatrix() 方法效果很好。但是,我认为问题在于 2 方法 operator+ 和 operator- 我认为 (A + B).printMatrix() 和 (A - B).printMatrix() 存在一些问题,但我无法弄清楚。每当我删除这两行时,程序就可以了。
-
如果您将它们注释掉,问题会消失吗?
-
转到您的调试 -> 异常 -> win32 异常,然后单击访问冲突旁边的复选框。这将使调试器停止访问冲突。当它停止时,将调用堆栈向上移动到程序中的代码行。
-
@drescherjm 你是对的,但如果应用了三规则,这将不是问题;本地结果将被复制。