【发布时间】: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