简体   繁体   English

C ++ operator +和operator + =重载

[英]C++ operator+ and operator+= overloading

I'm implementing my own matrix class in c++ to help me develop my understanding of the language. 我正在用c ++实现我自己的矩阵类,以帮助我培养对语言的理解。 I read somewhere that if you've got a working += operator, to use it in your + operator. 我读到某个地方,如果你有一个工作+ =运算符,在你的+运算符中使用它。 So that's what I've got: 这就是我所拥有的:

template <class T>
const Matrix<T>& Matrix<T>::operator+(const Matrix<T> &R){

    Matrix<T> copy(*this);
    return copy += R;
}

And here is the += operator overload: 这是+ =运算符重载:

template <class T>
const Matrix<T>& Matrix<T>::operator+=(const Matrix<T> & second_matrix){
    //Learn how to throw errors....
    if (rows != second_matrix.getNumRows() || cols != second_matrix.getNumCols()){throw "Dimension mismatch.";}
    int i,j;
    for (i = 0; i < rows; i++){
        for (j = 0; j < cols; j++){
            data[i][j] += second_matrix.get(i,j);
        }
    }
    return *this;
}

I can use the += just fine (eg, a += b; returns no errors). 我可以使用+ =就好了(例如,a + = b;不返回任何错误)。 But calling the + operator (eg, a = b + c;) returns : 但是调用+运算符(例如,a = b + c;)会返回:

test.cpp.out(77055) malloc: *** error for object 0x300000004: pointer being freed was not allocated

Just for completeness, here's my destructor: 为了完整,这是我的析构函数:

template <class T>
Matrix<T>::~Matrix(){
    for (int i = 1; i < rows; i++){
        delete[] data[i]; }
    delete[] data;
}

I've been using C++ for a couple years on and off, and still have trouble sometimes keeping track of pointers. 我一直在使用C ++几年,并且有时候仍然有问题跟踪指针。 I hope that's normal... Any help would be great. 我希望这是正常的......任何帮助都会很棒。 Thanks! 谢谢!

EDIT: here's my copy constructor. 编辑:这是我的复制构造函数。 It was set to free the data arrays but i removed that. 它被设置为释放数据阵列,但我删除了它。 now I get segmentation faults. 现在我得到了分段错误。

template <class T>
Matrix<T>::Matrix(const Matrix<T>& second_matrix){

    rows = second_matrix.getNumRows();
    cols = second_matrix.getNumCols();
    data = new T*[rows];

    int i,j;
    for (i = 0; i < rows; i++){
        data[i] = new T[cols];
    }
    for (i = 0; i < rows; i++){
        for (j = 0; j < cols; j++){
            data[i][j] = second_matrix.get(i,j);
        }
    }

}

operator+()不应返回引用类型,因为它是一个保存操作结果的新(本地声明的)实例。

If this a matrix for 3D rendering/simulation I would recommend NOT dynamically allocating the memory like that. 如果这是一个用于3D渲染/模拟的矩阵,我建议不要像这样动态分配内存。 You can end up with the memory being spread all over the place which causes caching issues. 你最终可能会将内存传播到整个地方,从而导致缓存问题。 It also leads to potential memory bugs. 它还会导致潜在的内存错误。

template <typename T>
class Matrix
{
   public:
      T   m_Data[4][4];
};

or if you want something non-4x4 或者如果你想要非4x4的东西

template <typename T, unsigned int rows, unsigned int columns>
class Matrix
{
   public:
      T   m_Data[rows][columns];
};

and then dynamically allocate the Matrix objects. 然后动态分配Matrix对象。

This is how I have implemented such operators for a Matrix class , this is based on a Vector Class . 这就是我为Matrix类实现这样的运算符的方法,它基于Vector类 Once you define some operators all other should be defined in terms of the simplest operators: 一旦定义了一些运算符,所有其他运算符都应该根据最简单的运算符来定义:

Matrix::Matrix(const Matrix& rMatrix) :
    _iRows(rMatrix._iRows), _iColumns(rMatrix._iColumns), _pVector(0)
{
    _pVector = new Vector[_iRows];
    for (int i = 0; i < _iRows; i++) { _pVector[i] = rMatrix._pVector[i]; }
}

Matrix& Matrix::operator=(const Matrix& rMatrix)
{
    if (this != &rMatrix)
    {
        if (0 != _pVector) { delete[] _pVector; pVector = 0; }
        _iRows = rMatrix._iRows;
        _iColumns = rMatrix._iColumns;
        _pVector = new Vector[_iRows];
        for (int i = 0; i < _iRows; i++) { _pVector[i] = rMatrix._pVector[i]; }
    }
    return *this;
}
Matrix& Matrix::operator+=(const Matrix& rMatrix)
{
    *this = *this + rMatrix;
    return *this;
}

Matrix Matrix::operator+(const Matrix& rMatrix) const
{
    Matrix matrix(_iRows, _iColumns);
    ValidateSizes(rMatrix);
    for (int i = 0; i < _iRows; i++) { matrix._pVector[i] = _pVector[i] + rMatrix._pVector[i]; }
    return matrix;
}

Matrix operator+(const Matrix& rMatrix, double dNum)
{
    Matrix matrix(rMatrix._iRows, rMatrix._iColumns);
    matrix.ValidateSizes(rMatrix);
    for (int i = 0; i < matrix._iRows; i++) { matrix._pVector[i] = dNum + rMatrix._pVector[i]; }
    return matrix;
}

Matrix operator+(double dNum, const Matrix& rMatrix)
{
    return operator+(rMatrix, dNum);
}

bool Matrix::ValidateSizes(const Matrix& rMatrix) const
{
    if (_iRows != rMatrix._iRows) { /* THROW EXCEPTION */ }
    if (_iColumns != rMatrix._iColumns) { /* THROW EXCEPTION */ }
    return true;
}

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

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