我们可以将引用绑定到函数的返回值吗

Can we bind a reference to a return value of a function?

本文关键字:函数 返回值 绑定 引用 我们      更新时间:2023-10-16

这是我的问题:

我有两个类VectorMatrix,我定义了两个函数,一个用于计算向量和矩阵的乘积,另一个用于将值分配给新向量。

这是代码:

  file: Matrix.cpp
  Vector Matrix::operator*(const Vector& v)const {
      assert(v.length == numRows);
      Vector temp(v.length);
      for (int j = 0; j < numCols; j++)
          for (int k = 0; k < v.length; k++)
              temp.contents[j] += v.contents[k] * contents[k][j];
      return temp;
  };
  file: Vector.cpp
  Vector& Vector::operator=(Vector& v){
      assert(v.length == length);
      if (&v != this) {
          for (int i = 0; i < length; i++)
              setComponent(i, v.contents[i]);
      }
      return *this;
   };

假设我已经很好地定义了一个4*4矩阵m1和一个1*4向量v1这是我在main()函数中的部分代码

  file: main.app
  Vector v2(4);
  v2 = m1 * v1;

它可以编译,但会遇到问题。

有人能给我一个如何处理这件事的提示吗?是因为我试图将引用与函数的返回值绑定吗?非常感谢!

在代码中,您定义了类似Vector& Vector::operator=(Vector &v)的赋值运算符。但它应该像Vector& Vector::operator=(Vector const & v)一样。原因是Vector &v指的是lvalue引用。但是CCD_ 10返回一个CCD_。

写入0x00….04地址是从空ptr偏移4个字节。这意味着您正试图通过未初始化的指针进行写入。如果您使用调试器,您可以找到尝试执行此操作的确切代码。

注意不要与std::vector发生名称冲突。假设您有构造函数,复制构造函数(下面给出,也需要赋值运算符),它可以正确分配并将所有元素初始化为零

Vector::Vector(int sz) {
  contents = new int[length = sz]; // allocation
  for (int i = 0; i < sz; i++) {
    contents[i] = 0;
  }
}
Vector::Vector(const Vector& v) {
  contents = new int[length = v.length]; // allocation
  for (int i = 0; i < length; i++) {
    contents[i] = v.contents[i];
  }
}
Matrix::Matrix(int rows, int cols) {
  contents = new int *[numRows = rows]; // allocation
  for (int i = 0; i < rows; i++) {
    contents[i] = new int[numCols = cols]; // allocation
    for (int j = 0; j < cols; j++) {
      contents[i][j] = 0;
    }
  }
}
Matrix::Matrix(const Matrix& m) {
  contents = new int *[numRows = m.numRows]; // allocation
  for (int i = 0; i < numRows; i++) {
    contents[i] = new int[numCols = m.numCols]; // allocation
    for (int j = 0; j < numCols; j++) {
      contents[i][j] = 0;
    }
  }
}