[英]I can't assign value to object in list c++
I have struct Point, it contains setters for x and y:我有 struct Point,它包含 x 和 y 的设置器:
struct Point {
int x;
int y;
Point() {
x = 0;
y = 0;
}
Point(int _x, int _y) {
x = _x;
y = _y;
}
Point& operator=(Point other) {
swap(x, other.x);
swap(y, other.y);
return *this;
}
void setX(int _) { x = _; }
void setY(int _) { y = _; }
};
Also I have Element for bidirectional list, its data is Point:我也有用于双向列表的元素,它的数据是点:
struct Element {
Point data;
Element *left;
Element *right;
Element(Point data) {
this->data = data;
left = right = this;
}
};
And also I created List structure, Point get(int i) returns Point I want to change:我还创建了 List 结构,Point get(int i) 返回我要更改的 Point:
struct List {
Element *first;
Element *last;
int length;
List() {
first = last = nullptr;
length = 0;
}
Point add(Point data) {
Element *e = new Element(data);
length++;
if (!last) {
first = last = e;
return data;
}
e->left = last;
last = last->right = e;
return data;
}
Point get(int i) {
if (i >= length && i<0) return Point();
Element *t = first;
while(i--) t = t->right;
return t->data;
}
};
Then in main I create List, I add Point to this list and then I try to change x and y values, but they don't change:然后在 main 中创建列表,将 Point 添加到此列表中,然后尝试更改 x 和 y 值,但它们没有改变:
int main() {
....
List snake;
snake.add(Point(3,4));
cout << snake.get(0).x << " " << snake.get(0).y << endl;
snake.get(0).setX(99);
snake.get(0).setY(99);
cout << snake.get(0).x << " " << snake.get(0).y << endl;
.....
}
Please, help?请帮忙? Why don't x and y values change and how to fix it?
为什么 x 和 y 值不改变以及如何解决?
This method:这种方法:
Point get(int i) {
if (i >= length && i<0) return Point();
Element *t = first;
while(i--) t = t->right;
return t->data;
}
returns a Point
by value.按值返回一个
Point
。 The object returned is not the object in the list.返回的 object 不是列表中的 object。 Hence here:
因此在这里:
snake.get(0).setX(99);
You do setX(99)
of a Point
, but that Point
is the temporary object returned from get
.您对
Point
执行setX(99)
,但该Point
是从get
返回的临时 object 。 You probably want to return a reference instead.您可能想要返回一个引用。 However, then you need to find a different solution for
if (i >= length && i<0) return Point();
但是,您需要为
if (i >= length && i<0) return Point();
找到不同的解决方案。 , ie the case when the index is out of bounds, because you cannot return a reference to a local variable. ,即索引超出范围的情况,因为您不能返回对局部变量的引用。 You can either throw an exception or simply assume that the passed index is a valid one.
您可以抛出异常或简单地假设传递的索引是有效的。 Change it to:
将其更改为:
Point& get(int i) {
//^ return reference
//if (i >= length && i<0) return Point();
//^^ DO NOT return a reference to ^^ local object !!!
Element *t = first;
while(i--) t = t->right;
return t->data;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.