【问题标题】:Overloading member operator,?重载成员运算符,?
【发布时间】:2021-12-26 18:47:01
【问题描述】:
#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;
    }
}

此代码的灵感来自 DLib 库中的 matrix class。

此代码允许分配用逗号分隔的文字值,如下所示:

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

请注意,您不能这样做:

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

这是因为构造函数不能返回对另一个对象的引用,这与operator= 不同。

在此代码中,如果 literal_assignment_helper::operator, 不是 const,则这种数字链接不起作用,逗号分隔的数字被视为逗号分隔的表达式。

为什么操作符必须是 const?这里有什么规则?

另外,不是 const 的operator, 有什么影响?它会被调用吗?

【问题讨论】:

  • 嗯,一个方法必须是 const 才能在 const 对象上调用。 , 通过 const 引用返回。如果你想让, 非常量,请通过非常量引用返回。

标签: c++ oop operator-overloading overloading operator-keyword


【解决方案1】:
const literal_assignment_helper& operator,(int number) const;

帮助程序和矩阵中的逗号运算符都返回一个 const 引用。因此,要在该引用上调用成员,成员函数/运算符必须是 const 限定的。

如果你删除所有的常量,比如

literal_assignment_helper& operator,(int number);

这似乎也有效。

【讨论】:

    猜你喜欢
    • 2012-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-05
    • 2012-02-01
    • 2023-03-30
    相关资源
    最近更新 更多