gpt4 book ai didi

c++ - 需要左值作为赋值的左操作数 - 数组

转载 作者:太空宇宙 更新时间:2023-11-04 14:39:38 27 4
gpt4 key购买 nike

下面是错误所在的代码片段,行

a[i][j] = m[i][j] + w[i][j];

返回错误

lvalue required as left operand of assignment

我找不到适用于数组的答案,我的矩阵定义如下:

Matrix::Matrix() {
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
coords[i][j] = 0.0f;
}

const Matrix operator+(const Matrix &m, const Matrix &w) {
Matrix a;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 4 ; j++)
a[i][j] = m[i][j] + w[i][j]; // <----- error
return a;
}

这里是运算符[]如何通过引用返回

const Vector Matrix::operator[](int i) const{
switch(i)
{
case 0: return Vector (coords[i][0], coords[i][1], coords[i][2]);
case 1: return Vector (coords[i][0], coords[i][1], coords[i][2]);
case 2: return Vector (coords[i][0], coords[i][1], coords[i][2]);
}
}

最佳答案

错误实际上是“lvalue required as left operand of assignment”。

这意味着您的a[i][j] 为您提供了一个临时对象。当您按值从函数返回时会发生这种情况。按值返回的函数调用是右值 表达式,您不能将右值表达式用作赋值的左操作数。您需要在 MatrixMatrix::operator[] 返回的辅助类上更改 operator[] 的实现,以便它们通过引用返回。通过引用返回的函数调用是左值表达式,您可以对其进行赋值。

template <typename T>
Vector<T>& Matrix<T>::operator[](int index) { ... }
template <typename T>
T& Vector<T>::operator[](int index) { ... }

当然,这是有道理的。如果您的 operator[] 没有通过引用返回,那么分配给它们返回的值将如何影响 Matrix 的内容?


响应您的编辑:

您的类(class)设计有问题。 Matrix 类似乎存储了一个 3×3 的 float 数组,称为 coords。但是,当您使用 Matrix::operator[] 时,它将一行 coords 中的值复制到 Vector 对象中。它们是拷贝。然后,您按值返回该 Vector,这会将 Vector 及其包含的值复制到函数之外。您对返回的 Vector 所做的任何操作都只会影响该拷贝。

除此之外,您的 switch 语句完全没有意义。每个案例都完全一样。您只需要使用 i 作为数组索引,而不是打开它。

此外,如果您要允许调用 operator[] 的人修改您的 Matrix 的内容,那么 operator[] 函数不能是 const

有几种替代方法可以解决您的问题。第一种是只返回一个 float* 并用 Vector 废弃你的计划:

float* Matrix::operator[](int i) {
return coords[i];
}

这是一个非常简单的解决方案,但涉及传递原始指针。原始指针可以像数组一样使用,允许语法 m[i][j]

您可以像 Eigen 库一样做,而是提供一个带有两个参数的 operator(),行索引和列索引:

float& Matrix::operator()(int i, int j) {
return coords[i][j];
}

请注意,float 是通过引用返回的:float&。这意味着可以从对 operator() 的调用之外进行修改。在这里,您将使用 m(i, j) 索引一行和一列。

关于c++ - 需要左值作为赋值的左操作数 - 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14832847/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com