Search code examples
c++functionassignment-operator

How do I declare a function that can perform an assignment operation? (C++)


I am trying to create a function similar to the at() function in std::vector. I know how to overload the operator for = but this is not what I am after. I have a matrix object and I am looking to perform an operation along the lines of overwriting a column vector of the matrix, i.e.

int rowNumber = 3; int columnNumber = 3;
Matrix myMatrix(rowNumber, columnNumber);
Vector myColumnVector(rowNumber);
myMatrix.col(2) = myColumnVector;

where col() is the assignment function. How do I declare this function?


Solution

  • You might use some proxy:

    struct Matrix;
    
    struct ColWrapper
    {
        Matrix* mMatrix;
        int mIndex;
    
        ColWrapper& operator =(const std::vector<double>& d);
    };
    
    struct RowWrapper
    {
        Matrix* mMatrix;
        int mIndex;
    
        RowWrapper& operator =(const std::vector<double>& d);
    };
    
    struct Matrix
    {
        std::vector<double> mData;
        int mRow;
    
        Matrix(int row, int column) : mData(row * colunmn), mRow(row) {}
    
    
        ColWrapper col(int index) { return {this, index}; }
        RowWrapper row(int index) { return {this, index}; }
    };
    
    ColWrapper& ColWrapper::operator =(const std::vector<double>& ds)
    {
        auto index = mIndex * mMatrix->mRow;
    
        for (auto d : ds) {
            mMatrix->mData[index] = d;
            index += 1;
        }
        return *this;
    }
    
    RowWrapper& RowWrapper::operator =(const std::vector<double>& ds)
    {
        auto index = mIndex;
    
        for (auto d : ds) {
            mMatrix->mData[index] = d;
            index += mMatrix->mRow;
        }
        return *this;
    }