gpt4 book ai didi

c++ - 修改对象与修改该对象的拷贝

转载 作者:行者123 更新时间:2023-11-28 00:54:35 25 4
gpt4 key购买 nike

我已尝试尽可能地对我的问题进行 SSCE,但它涉及用 C++ 定义的多个对象。不过它们很​​简单 - 我认为最好在进一步解释之前分享我的代码:

#include <iostream>
#include <vector>

struct Cell {
bool visited;
Cell():visited(false) {}
void setVisited(bool val) {visited = val;}
bool beenVisited() {return visited;}
};
struct Vector2D
{
int size;
std::vector<Cell> myVector;
Vector2D(int n): size(n), myVector(n*n) {}
Cell& getAt(int x, int y) {return myVector[((x * size) +y)];}
};

int main()
{
Vector2D vec = Vector2D(1);
Cell cell= vec.getAt(0,0);

cell.setVisited(true);
cell = vec.getAt(0,0);
if (cell.beenVisited() == false)
std::cout << "Why is this not true like I set it a moment ago?\n";
}

对于所有这一切,我深表歉意,但这是说明问题所必需的。如您所见,我 getAt() 我认为是 Cell 对象,将其访问的实例数据设置为 true,然后切换到另一个单元格。那么,为什么当我回到同一个单元格时,发现访问的值是 false 而不是 true?!好像它没有注册我的私有(private)数据更改!

执行此操作的最佳方法是什么?

谢谢

最佳答案

Cell cell= vec.getAt(0,1);

对象的拷贝。使用

Cell& cell = vec.getAt(0, 1);

或简单地

vec.getAt(0, 1).setVisited(true);

编辑。

这段代码应该可以工作。

using namespace bob;
Vector2D vec = Vector2D(5);
vec.setAt(0,0, Cell(0,0));
vec.setAt(0,1, Cell(0,1));
vec.setAt(0,2, Cell(0,2));
Cell& cell= vec.getAt(0,1);

cell.setVisited(true);
Cell cell1 = vec.getAt(0,2);
cell1 = vec.getAt(0,1);
if (cell1.beenVisited() == false)
{
std::cout << "Why is this not true like I set it a moment ago?" << std::endl;
}

http://liveworkspace.org/code/53634eda052a07885d4e6c062a0fd302

关于c++ - 修改对象与修改该对象的拷贝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12218655/

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