代码之家  ›  专栏  ›  技术社区  ›  DangerousTim

使用重载运算符时出现分段错误

  •  0
  • DangerousTim  · 技术社区  · 8 年前

    代码中的以下行导致了一个神秘的segfault:

    N = N + M;
    

    其中N和M是矩阵类的对象:

    class Matrix {
        vector<int> A; 
        int m, n;
    }
    

    +操作员功能:

    Matrix Matrix::operator+(const Matrix &other){
        //matrices must be of same dimensions
        //if not, return null Matrix
        if (m != other.m || n != other.n)
            return Matrix(0, 0);
    
        Matrix T(m, n);
        for (int i = 0; i < m*n; i++){
            T.A.at(i) = this->A.at(i) + other.A.at(i);
        }
        return T;
    }
    

    当然,N和M的大小相同(3x3)。

    即使出现以下情况,也会出现segfault:

    M = N + M;
    

    M = M + N;
    

    Matrix P;
    P = M + N;
    

    但是 不适用于 :

    Matrix P = M + N;
    

    我可能犯了什么错误?我是C++新手。

    编辑: 下面是=运算符:

    Matrix Matrix::operator=(const Matrix &other){
        A = other.A;
        m = other.m, n = other.n;
    }
    

    编辑2 :我的构造函数很有用

    Matrix::Matrix(int r, int c):
        m(r), n(c), A(r*c)
    { }
    
    1 回复  |  直到 8 年前
        1
  •  0
  •   GuyRT    8 年前

    我认为问题在于您的赋值运算符:

    Matrix Matrix::operator=(const Matrix &other){
        A = other.A;
        m = other.m, n = other.n;
    }
    

    您将其声明为返回 Matrix 对象,但实际上不返回任何内容。

    解决方案(请注意,返回类型现在是一个参考):

    Matrix &Matrix::operator=(const Matrix &other){
        A = other.A;
        m = other.m, n = other.n;
        return *this;
    }
    

    请注意,默认编译器生成的赋值无论如何都是正确的。因此,更好的解决方案是使用该方法(在类声明中):

    Matrix &operator=(const Matrix &other) = default;