如何声明可以执行赋值操作的函数?(C++)

How do I declare a function that can perform an assignment operation? (C++)

本文关键字:操作 C++ 赋值 函数 何声明 声明 执行      更新时间:2023-10-16

我正在尝试创建一个类似于std::vector中的at()函数的函数。我知道如何使操作员超载=但这不是我所追求的。我有一个矩阵对象,我希望按照覆盖矩阵的列向量的方式执行操作,即

int rowNumber = 3; int columnNumber = 3;
Matrix myMatrix(rowNumber, columnNumber);
Vector myColumnVector(rowNumber);
myMatrix.col(2) = myColumnVector;

其中col()是赋值函数。如何声明此函数?

您可以使用一些代理:

struct Matrix;
struct ColWrapper
{
Matrix* mMatrix;
int mIndex;
ColWrapper& operator =(const std::vector<double>& d);
};
struct RowWrapper
{
Matrix* mMatrix;
int mIndex;
RowWrapper& operator =(const std::vector<double>& d);
};
struct Matrix
{
std::vector<double> mData;
int mRow;
Matrix(int row, int column) : mData(row * colunmn), mRow(row) {}

ColWrapper col(int index) { return {this, index}; }
RowWrapper row(int index) { return {this, index}; }
};
ColWrapper& ColWrapper::operator =(const std::vector<double>& ds)
{
auto index = mIndex * mMatrix->mRow;
for (auto d : ds) {
mMatrix->mData[index] = d;
index += 1;
}
return *this;
}
RowWrapper& RowWrapper::operator =(const std::vector<double>& ds)
{
auto index = mIndex;
for (auto d : ds) {
mMatrix->mData[index] = d;
index += mMatrix->mRow;
}
return *this;
}

col()不是赋值函数。

operator=()是分配功能。

col()是计算您将要分配给的事物的函数。在这种情况下,对Vector的引用(即Vector&( 将完成这项工作。