【问题标题】:How do I declare a function that can perform an assignment operation? (C++) [closed]如何声明可以执行赋值操作的函数? (C++)[关闭]
【发布时间】:2019-08-10 16:33:54
【问题描述】:

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

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

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

【问题讨论】:

  • at() 返回一个引用。你熟悉参考文献吗?让你的函数返回一个引用。可能是一个带有operator= 重载的辅助对象。如果您不熟悉这些概念,我将不得不指导您阅读您的 C++ 书籍。两者都是非常广泛的主题,stackoverflow.com 并没有真正设置为定制的 C++ 教程网站。
  • 有一个 Matrix::col() 函数返回对基础数据类型的引用。添加更多关于您的 Matrix 类是如何定义的信息,以便在此处接收一些简明的答案。

标签: c++ function assignment-operator


【解决方案1】:

您可能会使用一些代理:

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;
}

【讨论】:

    【解决方案2】:

    col() 不是赋值函数。

    operator=()是赋值函数。

    col() 是评估您将分配给的事物的函数。在这种情况下,对Vector(即Vector&amp;)的引用就可以完成这项工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-01
      • 2010-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      相关资源
      最近更新 更多