簡體   English   中英

使用重載運算符時出現分段錯誤

[英]Segmentation fault when using overloaded operator

我的代碼中的以下行引起了神秘的段錯誤:

N = N + M;

其中N和M是Matrix類的對象:

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)。

即使出現以下情況,段錯誤也會出現:

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)
{ }

我認為問題出在您的賦值運算符上:

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM