如何声明可以执行赋值操作的函数?(C++)
How do I declare a function that can perform an assignment operation? (C++)
我正在尝试创建一个类似于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&
( 将完成这项工作。
相关文章:
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 重载操作程序时出错>>用于类中的字符串 memebr
- 对字符串进行位操作
- 我可以在 C++ 中的函数体之外进行操作吗?
- MPI突然停止了对多个核心的操作
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- 对字符数组中的元素执行逐位操作
- 如何在directx/c++中进行平移/缩放操作
- 逐位操作的隐式类型转换
- 为什么一个向量上的多线程操作很慢
- 排序时无法执行交换操作.我做的时候它会崩溃.为什么
- 位移操作和位掩码未检测到重复字符
- 如何进行特定的位操作?
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 字符串操作 - 字符计数
- 此代码中的操作流程是什么?C/C++.
- 复制和交换习惯用法与移动操作之间的交互
- 像union_这样的 Boost.Geometry 操作如何处理浮点类型的基本不精确性?
- 为什么 std::lerp 不适用于任何已实现所需操作的类型?
- 无法合并生成操作.. 先决条件不同