簡體   English   中英

重載運算符'+'和'='C ++

[英]overloading operators '+' and '=' C++

我最近開始學習C ++,現在我正在研究Matrix類。 我正在嘗試重載運算符,結果比我想象的要困難得多。 因此,我已經重載了'='和'+',當我只想將一個矩陣設置為等於另一個矩陣時,第一個可以正常工作,但是當我執行類似'matrix = matrix1 + matrix2'的操作時,它崩潰了,沒有錯誤。 如果有人幫助我,我將非常感激。 這是我的代碼:

class Matrix
{
private:
    int lines , columns;
    int *Matrix_Numbers;
public:
    Matrix();

    Matrix(int n , int m)
    {
        lines = n , columns = m;
        Matrix_Numbers = new int[lines * columns];
    }

    Matrix & operator = (Matrix &mat);

    Matrix & operator + (Matrix &mat);

    ~Matrix()
    {
        delete Matrix_Numbers;
    }
};

Matrix & Matrix::operator = (Matrix &mat)
{
    this -> lines = mat.lines;
    this -> columns = mat.columns;
    int i , j;
    for(i = 0 ; i < lines ; i++)
    {
        for(j = 0 ; j < columns ; j++)
        {
            this -> Matrix_Numbers[i * (this -> columns) + j] = mat(i , j);
        }
    }
    return *this;
}

Matrix & Matrix::operator + (Matrix &mat)
{
    Matrix result(lines , columns);
    if(mat.lines == lines && mat.columns == columns)
    {
        int i , j;
        for(i = 0 ; i < lines ; i++)
        {
            for(j = 0 ; j < columns ; j++)
            {
                result.Matrix_Numbers[i * columns + j] = Matrix_Numbers[i * 
                                            columns + j] + mat(i , j);
            }
        }
    }
    else
    {
        cout << "Error" << endl;
    }
    return result;
}

當然,這只是我的代碼的一部分,還有更多,但是我認為這是破碎的部分。 如果您需要更多信息,請與我們聯系:)

您的operator+方法返回對結果的引用。 唯一的問題是result是一個局部變量,這意味着它在方法返回時被銷毀。 您應該按值返回它,並讓編譯器優化內容。

就像注釋中指出的其他內容一樣,您應盡可能使用const,以便實際上可以使用常量參數來調用operator+

暫無
暫無

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

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