简体   繁体   English

重载成员运算符,?

[英]Overloading member operator,?

#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.此代码的灵感来自DLib库中的矩阵 class

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= .这是因为构造函数不能返回对另一个 object 的引用,这与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.在此代码中,如果literal_assignment_helper::operator,不是 const,则这种数字链接不起作用,逗号分隔的数字被认为是逗号分隔的表达式。

Why must the operator be const?为什么运算符必须是 const? What are the rules here?这里有什么规则?

Also, what is the impact of an operator, that is not const?另外,不是 const 的operator,有什么影响? Is it ever going to be called?它会被调用吗?

const literal_assignment_helper& operator,(int number) const;

The comma operators, both in the helper and in the Matrix, return a const reference.帮助程序和矩阵中的逗号运算符都返回一个 const 引用。 So to call a member on that reference, the member function/operator has to be const qualified.因此,要在该引用上调用成员,成员函数/运算符必须是 const 限定的。

If you remove all the constness, like如果你删除所有的常量,比如

literal_assignment_helper& operator,(int number);

that also seems to work.这似乎也有效。

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

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