简体   繁体   English

重载运算符'+'和'='C ++

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

I've recently started learning C++, right now I'm working on a Matrix Class. 我最近开始学习C ++,现在我正在研究Matrix类。 I'm trying to overload operators and it turned out to be more difficult than I thought. 我正在尝试重载运算符,结果比我想象的要困难得多。 So I've overloaded '=' and '+', first one works perfectly fine when I just want to set one matrix equal to another, but when I do something like 'matrix = matrix1 + matrix2' it crashes with no error. 因此,我已经重载了'='和'+',当我只想将一个矩阵设置为等于另一个矩阵时,第一个可以正常工作,但是当我执行类似'matrix = matrix1 + matrix2'的操作时,它崩溃了,没有错误。 I'd be very thankful if someone helps me. 如果有人帮助我,我将非常感激。 Here's my code: 这是我的代码:

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;
}

Of course it's just a part of my code, there's more, but I thought that this is the broken part. 当然,这只是我的代码的一部分,还有更多,但是我认为这是破碎的部分。 Let me know if you need more information:) 如果您需要更多信息,请与我们联系:)

Your operator+ method returns a reference to the result. 您的operator+方法返回对结果的引用。 The only problem is that result is a local variable which means it gets destroyed upon the method returning. 唯一的问题是result是一个局部变量,这意味着它在方法返回时被销毁。 You should return it by value instead and let the compiler optimize stuff. 您应该按值返回它,并让编译器优化内容。

Like others pointed out in the comments, you should use const whenever possible so your operator+ can actually be called with constant parameters. 就像注释中指出的其他内容一样,您应尽可能使用const,以便实际上可以使用常量参数来调用operator+

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

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