Home > Back-end >  Overloading member operator,?
Overloading member operator,?

Time:12-27

#include <iostream>
#include <vector>

struct Matrix;

struct literal_assignment_helper
{
    mutable int r;
    mutable int c;
    Matrix& matrix;

    explicit literal_assignment_helper(Matrix& matrix)
            : matrix(matrix), r(0), c(1) {}

    const literal_assignment_helper& operator,(int number) const;
};

struct Matrix
{
    int rows;
    int columns;
    std::vector<int> numbers;

    Matrix(int rows, int columns)
        : rows(rows), columns(columns), numbers(rows * columns) {}

    literal_assignment_helper operator=(int number)
    {
        numbers[0] = number;
        return literal_assignment_helper(*this);
    }

    int* operator[](int row) { return &numbers[row * columns]; }
};

const literal_assignment_helper& literal_assignment_helper::operator,(int number) const
{
    matrix[r][c] = number;

    c  ;
    if (c == matrix.columns)
        r  , c = 0;

    return *this;
};


int main()
{
    int rows = 3, columns = 3;

    Matrix m(rows, columns);
    m = 1, 2, 3,
        4, 5, 6,
        7, 8, 9;

    for (int i = 0; i < rows; i  )
    {
        for (int j = 0; j < columns; j  )
            std::cout << m[i][j] << ' ';
        std::cout << std::endl;
    }
}

This code is inspired by the matrix class in the DLib library.

This code allows for assigning literal values separated by commas like this:

Matrix m(rows, columns);
m = 1, 2, 3,
    4, 5, 6,
    7, 8, 9;

Note that you can't do something like this:

Matrix m = 1, 2, 3, ...

This is because the constructor can't return a reference to another object, unlike the operator=.

Here in this code, if literal_assignment_helper::operator, is not const, this chaining of numbers doesn't work, the comma-separated numbers are considered to be comma-separated expressions.

Why must the operator be const? What are the rules here?

Also, what is the impact of an operator, that is not const? Is it ever going to be called?

CodePudding user response:

const literal_assignment_helper& operator,(int number) const;

The comma operators, both in the helper and in the Matrix, return a const reference. So to call a member on that reference, the member function/operator has to be const qualified.

If you remove all the constness, like

literal_assignment_helper& operator,(int number);

that also seems to work.

  • Related