C ++程序构建成功,但运行时出错

时间:2016-04-24 18:48:05

标签: c++

Matrix &Matrix::operator*(Matrix &rhs) {
    if (this->columns != rhs.rows) {
        this->~Matrix();
        return *this;
    }
    else {
        Matrix product(this->rows, rhs.columns);


        /*for (unsigned int col = 0; col < product.columns; col++) {
            for (unsigned int row = 0; row < product.rows; row++) {
                unsigned int val = 0;
                for (unsigned int i = 0; i < this->columns; i++) {
                    val += this->get(row, i)*rhs.get(i, col);
                }
                product.set(row, col, val);
            }
        }*/

        return product;
    }

代码构建,但在运行时崩溃。在调试时,我得到错误位于复制构造函数(this->matrix = new double[rows*columns];

中的消息
Matrix::Matrix(const Matrix&m):rows(m.rows),columns(m.columns),matrix(nullptr) {
    if (!m.isValid()) {
        return;
    }
    this->matrix = new double[rows*columns];
    for (unsigned int i = 0; i < rows*columns; i++) {
        matrix[i] = m.matrix[i];
    }
}

我不明白为什么?在我实现*运算符之前,复制构造函数正在运行。我一点一点地评论找出真正的错误,看起来程序因返回产品而崩溃;声明。这就是我已经注释掉了for循环,所以那些不是问题。

我对main的测试很简单:

#include "Source.h"
#include "Matrix.h"
#include<iostream>

int main() {
    Matrix A(3,3);
    Matrix B(3);
    cout << B << endl;
    cout << A << endl;
    Matrix C=A*B;
    cout << C << endl;

    return 0;
}

我希望有人能帮助我,因为我真的被困了。 以下是整个计划的链接:

1 个答案:

答案 0 :(得分:2)

代码中的operator *方法返回对局部变量的引用。局部变量product超出范围并在return时被销毁,因此您最终返回一个悬空引用,使用它可能最终导致未定义的行为。

operator *的返回类型应该只是Matrix而不是Matrix &

Matrix Matrix::operator*(Matrix &rhs) { /* ... your code here ... */ }
相关问题