#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 m(rows, columns);
m = 1, 2, 3,
4, 5, 6,
7, 8, 9;
請注意,您不能執行以下操作:
Matrix m = 1, 2, 3, ...
這是因為建構式不能回傳對另一個物件的參考,與operator=.
在這段代碼中,如果literal_assignment_helper::operator,不是const,這種數字鏈不起作用,逗號分隔的數字被認為是逗號分隔的運算式。
為什么運算子必須是常量?這里的規則是什么?
另外,operator,非 const的影響是什么?它會被呼叫嗎?
uj5u.com熱心網友回復:
const literal_assignment_helper& operator,(int number) const;
幫助程式和 Matrix 中的逗號運算子回傳一個常量參考。因此,要在該參考上呼叫成員,成員函式/運算子必須是 const 限定的。
如果你洗掉所有的常量,比如
literal_assignment_helper& operator,(int number);
這似乎也有效。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/395607.html
上一篇:從同一個父類的另一個類訪問物件
