更改派生类对象的字段但返回后更改已恢复

时间:2021-08-01 17:41:15

标签: c++ abstract-class derived-class mutation

我覆盖了 create 函数。

void IBlock::create() {
    Cell a;
    a.setCoords(0, 3);
    a.setblank(false);
    Cell b;
    b.setCoords(1, 3);
    b.setblank(false);
    Cell c;
    c.setCoords(2, 3);
    c.setblank(false);
    Cell d;
    d.setCoords(3, 3);
    d.setblank(false);
    vector<Cell> row2;
    row2.push_back(a);
    row2.push_back(b);
    row2.push_back(c);
    row2.push_back(d);
    block.push_back(row2);
}

但是当我尝试在单元格中使用 IBlockright 更改 setX 的坐标并输出它们的坐标时,

void Board::right() {
    bool movable = true;
    if (getCurrent() == nullptr) {
        return;
    }
    for (auto ro : getCurrent()->block) {
        int x = ro.back().getX() + 1;
        int y = ro.back().getY();
        if (x >= col || (board[y][x])) {
            movable = false;
        }
    }
    if (movable) {
        for (auto ro : getCurrent()->block) {
            for (auto co : ro) {
                int x = co.getX();
                int y = co.getY();
                board[y][x] = false;
            }
        }

        for (auto ro : getCurrent()->block) {
            for (auto co : ro) {
                co.setX(co.getX() + 1);
                int x = co.getX();
                int y = co.getY();
                board[y][x] = true;
                cout << x << y << "!";
            }
        }
    }
}
void Cell::setX(int a)
{
    this->x = a;
}

我得到的坐标为 13!23!33!43!。 但是当我在 main 中获取坐标时,我得到的坐标为 03!13!23!33!,就像移动前的坐标一样?

我怎样才能保持坐标的变化?非常感谢你!!

1 个答案:

答案 0 :(得分:3)

for (auto co : ro) 使每个迭代对象渲染调用(如 co.setX() 无用)的副本。这就像按值传递参数一样。如果您需要循环(函数)来改变可迭代的元素(参数),请将它们绑定到一个引用循环变量(参数)。

使用 for (auto& co : ro),有关详细信息,请参阅 this answer

同样适用于 for (auto ro : getCurrent()->block) 循环,使用 const auto& 以避免额外的副本。