【问题标题】:Debug Assertion Failed error调试断言失败错误
【发布时间】:2015-02-13 21:04:19
【问题描述】:

我正在尝试为我正在做的项目重载 + 运算符,但这种情况一直在发生。我认为原因是我创建的对象在调用运算符时被删除。不知道如何解决它。这是我的部分代码:

Matrix Matrix::operator+ (const Matrix& m) const
{
    //something wrong here
    Matrix sum(rows, cols);

    for (int i = 0; i < cols; i++)
    {
        for (int j = 0; j < rows; j++)
        {
            sum.element[i][j] = this->element[i][j] + m.element[i][j];
        }
    }

    return sum;
}

附加信息

Matrix::Matrix(int r, int c)
{
    rows = r;
    cols = c;
    element = new int *[c];
    for (int i = 0; i < c; i++)
    {
        element[i] = new int[r];
    }
    for (int i = 0; i < cols; i++)
    {
        for (int j = 0; j < rows; j++)
        {
            element[i][j] = 0;
        }
    }
}


Matrix::Matrix(const Matrix& m)
{
    this->element = m.element;
}


Matrix::~Matrix()
{
    //freeing up the arrays
    for (int i = 0; i < cols; i++)
    {
        delete[] element[i];
        element[i] = NULL;
    }
    delete[] element;
    element = NULL;
}


Matrix& Matrix::operator= (const Matrix& m)
{
    //problem if rows and cols are longer in the new matrix
    //need to create a temp matrix to expand to new one
    for (int i = 0; i < cols; i++)
    {
        for (int j = 0; j < rows; j++)
        {
            this->element[i][j] = m.element[i][j];
        }
    }
    return *this;
}


int* Matrix::operator[] (int n)
{
    return element[n];
}

我得到的具体错误是:

调试断言失败!

表达式:_BLOCK_TYPE_IS_VALID(pHead->nBlockUse)

在第 52 行,我这样做了:

 Matrix total = mat + m;

其中mat和m都是对象矩阵

【问题讨论】:

  • 在不提供 Matrix 构造函数代码的情况下,您希望我们如何帮助您?尤其是断言错误。
  • 欢迎来到stackoverflow :)。我同意看到矩阵构造函数将帮助我们理解问题。包括你得到的具体错误也会很有用。
  • 感谢您的建议!已添加到帖子中。
  • matm 大小一样吗?
  • 你在你的程序中做任何复制吗?

标签: c++


【解决方案1】:

我猜这个问题是由这个引起的:

Matrix::Matrix(const Matrix& m)
{
    this->element = m.element;
}

这是一个无效的复制构造函数,有两个原因。首先,您没有初始化rowscols。其次,您现在将有两个 Matrix 对象指向同一个内存 - 这两个对象都会在销毁时将其删除:

{
    Matrix m1(3, 5);
    Matrix m2 = m1;
} // BOOM!

你需要在这里做一个深拷贝:

Matrix::Matrix(const Matrix& m)
: rows(m.rows), cols(m.cols)
{
    element = new int *[cols];
    for (int i = 0; i < cols; ++i) {
        element[i] = new int[rows];
        for (int j = 0; j < rows; ++j) {
            element[i][j] = m.element[i][j];
        }
    } 
}

【讨论】:

  • 非常感谢!我会投票,但我没有足够的声誉:(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-29
  • 2011-12-08
  • 2015-06-27
  • 1970-01-01
相关资源
最近更新 更多