繁体   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