c++ - 多维数组在循环中赋值 : expression must be a modifiable lvalue

标签 c++ arrays multidimensional-array 2d lvalue

所以在一个类中,我有一个这样的数组:

public:
    int playGrid[10][10];//size of the grid, 10x10 or 100 squares

当我这样做时:

        for (int i = iX1; i < iX2; i++)
        {
            if (i == iX1)
            {
                playGrid[i][iY1] = 4;
            }
        }

这个:

playGrid[i][iY1] = 4;

给我:

expression must be a modifiable lvalue

我不确定我在这里做错了什么。此代码位于该类的其中一个方法中,因此它可以访问它。我找遍了所有地方,但无法找到他们使用具有简单整数赋值的二维数组的示例。

感谢您的帮助!

编辑:需要更多代码,所以我们开始:

void Grid::placeBoat(int iX1, int iY1, int iX2, int iY2) const
{
    if (iX1 != iX2)
    {
        if (iX1 < iX2)
        {
            for (int i = iX1; i < iX2; i++)
            {
                if (i == iX1)
                {       
                    playGrid[i][iY1] = 4;
                }
            }
        }
        else
        {

        }
    }
    else if (iY1 != iY2)
    {

    }
}

这是网格类:

class Grid
{
public:
    int playGrid[10][10];//size of the grid, 10x10 or 100 squares
    void drawGrid() const;
    void placeBoat(int, int, int, int) const;
    Grid();
    ~Grid();
};

最佳答案

void Grid::placeBoat(int iX1, int iY1, int iX2, int iY2) const

看到定义末尾的const了吗?这意味着您可以在实例 (Grid) 为常量时调用此方法。

由于您允许该调用,因此编译整个函数体时假定 this 的类型为 const Grid *

然后您试图更改数组,它是 (const) Grid 的成员,因此会出现编译器错误。

关于c++ - 多维数组在循环中赋值 : expression must be a modifiable lvalue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48515526/

相关文章:

c++ - 转储对象的内存内容

c++ - 如何分隔数组中的奇数和偶数?

c++ - 正确使用模板将函数传递给线程池

python - 基于二维数组中的一列对数据进行分箱,并使用 cython 估计每个箱中的平均值

c - 在函数之间传递多维数组

c++ - 有没有办法限制访问文件的用户数量

php - 在 PHP 中过滤 JSON 数据

arrays - 在 verilog 中连接输入

C编程: how do you print the contents of a file after it's been dynamically allocated?

d3.js - D3 的多维数组