简体   繁体   English

一元减运算符重载 C++ 分段错误

[英]Unary minus operator overload C++ segmentation fault

I have an object Matrix and I overloaded the unary minus operator and I can't manage to make my program work.我有一个对象 Matrix 并且我重载了一元减号运算符,但我无法使我的程序正常工作。 If I put the return type as reference it does not allow me to return the object I created inside the function, if I put the return type as Matrix then I get segmentation fault.如果我将返回类型作为引用,它不允许我返回我在函数内部创建的对象,如果我将返回类型作为 Matrix 则我会得到分段错误。

in the H file :在 H 文件中:

Matrix operator - () const; 

in the cpp file:在 cpp 文件中:

Matrix Matrix::operator - () const
{
  if (isValid==false)//just a validity check
    return *this;

  Matrix mat(*this);//copy ctor

  for (int i=0;i<row;i++)
       for (int j=0;j<col;j++)
          mat.matrix[i][j]=-matrix[i][j];

  return mat;
}

I tried many permutations of that (adding const, adding by reference) and nothing seems to work.我尝试了很多排列(添加常量,通过引用添加),但似乎没有任何效果。 How do I fix this ?我该如何解决 ?

What follows works without any segmentation faults.接下来的工作没有任何分段错误。 You should minimize your code by removing anything unneccessary, then gradually transform it to the code below, and see at what stage your segmentation fault vanishes.您应该通过删除任何不必要的东西来最小化您的代码,然后逐渐将其转换为下面的代码,并查看您的分段错误在哪个阶段消失。

#include <iostream>
#include <vector>

using namespace std;

class Matrix {
public:
    Matrix() : isValid(true), row(0), col(0) {}
    Matrix(int r, int c, int val);
    Matrix(const Matrix&);
    Matrix operator - () const; 
private:
    bool isValid;
    int row, col;
    vector<vector<int> > matrix;
};

Matrix::Matrix(int r, int c, int val) : isValid(true), row(r), col(c) {
    matrix.resize(r);
    for (int i=0; i<r; i++)
        matrix[i].resize(c, val);
}

Matrix::Matrix(const Matrix& m) : isValid(true), row(m.row), col(m.col), matrix(m.matrix) {}

Matrix Matrix::operator - () const
{
  if (isValid==false)//just a validity check
    return *this;

  Matrix mat(*this);//copy ctor

  for (int i=0;i<row;i++)
       for (int j=0;j<col;j++)
          mat.matrix[i][j]=-matrix[i][j];

  return mat;
}

main() {
    int r=10, c=5;
    Matrix m(r, c, 1);
    Matrix m1;
    m1 = -m;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM