0

我有一个 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:(

4

2 回答 2

6

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

list<Component*>& Tab::getComponents() {
    return (this->components);
}
于 2012-10-04T23:43:31.167 回答
5

您的return而不是,这意味着在Tab::getComponents()返回时被复制。因此,让我们看一下代码:list<Component*>list<Component*>&this->components

list<Component*>::iterator it = activeTab->getComponents().begin(); 
// ``it'' is already INVALID here since the list returned in the above line
// is already destructed!
for (it ; it != activeTab->getComponents().end(); it++) {
    offset.x = (*it)->getX(); //``it'' is invalid
    cout << "offset.x = " << offset.x << endl;
    offset.y = (*it)->getY();
    cout << "offset.y = " << offset.y << endl;
}

it取消引用时迭代器无效。

于 2012-10-04T23:46:08.090 回答