gpt4 book ai didi

C++推前迭代

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

我有一个包含组件列表的 Tab 类。

list<Component*> Tab::getComponents() {
return (this->components);
}

void Tab::addComponent(Component* comp){
this->components.push_front(comp);
}

Tab::Tab() {
// x = 25, y = 30
Button* one = new Button(25,30,300,100, "images/button.png");
this->addComponent(one);

Button* two = new Button(75,100,300,100, "images/button.png");
this->addComponent(two);

// x = 150, y = 150
Button* three = new Button(150,150,300,100, "images/button.png");
this->addComponent(three);
}

现在是有问题的代码:

list<Component*>::iterator it = activeTab->getComponents().begin(); 
for (it ; it != activeTab->getComponents().end(); it++) {
offset.x = (*it)->getX();
cout << "offset.x = " << offset.x << endl;
offset.y = (*it)->getY();
cout << "offset.y = " << offset.y << endl;
}

这是 for 循环第一次迭代的输出:

offset.x = 25
offset.y = 30

但是,看到我使用了push_front(),应该是:

offset.x = 150
offset.y = 150

我做错了什么?

编辑:for 循环的第二次迭代打印垃圾...

offset.x = 16272
offset.y = 17

第三个只是打印segmentation fault :(

最佳答案

请注意您的方法 getComponents() 正在返回一个拷贝,您应该返回一个引用。

list<Component*>& Tab::getComponents() {
return (this->components);
}

关于C++推前迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12737444/

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