Linked-List仅记住最近添加的对象

时间:2014-03-19 21:42:11

标签: c++ pointers linked-list

我有一项任务,要求我将对象添加到链接列表中。有问题的对象是形状。

我的问题是我可以将对象添加到列表中,但是当我尝试将它们打印出来时,只打印最后添加的对象,其余的只是垃圾值。

我的代码如下所示:

Source.cpp:

#include "ShapeList.h"
#include <iostream>

using namespace std;

int main()
{
    ShapeList list;
    list.add(Rectangle(0,0,2,5));
    list.print();
}

我不允许更改此代码。例如,我不允许发送指向新矩形的指针,我应该&#34;深拷贝&#34;它。 (我希望我能正确使用这个词。)

我的ShapeList.h看起来像这样:

#ifndef SHAPELIST_H
#define SHAPELIST_H
#include "Shape.h"
#include "Rectangle.h"

class ShapeList
{
private:
    Shape *conductor; //this will point to each node as it traverses the list
    Shape *root; //the unchanging first node
public:
    ShapeList();
    void print();
    void add(const Shape &s);
};

#endif

,标题如下:

#include "ShapeList.h"
#include <iostream>
using namespace std;

ShapeList::ShapeList()
{
    cout << "ShapeList created" << endl;
    root = new Shape; //now root points to a node class
    root->next = 0; //the node root points to has its next  pointer set to equal a null pointer
    conductor = root; //the conductor points to the first node
}

void ShapeList::add(const Shape &s)
{
    cout << "Shapelist's add function called" << endl;
    conductor->next = new Shape; //creates node at the end of the list
    conductor = conductor->next; //goes to next node
    Shape *pShape = s.clone(); //get a pointer to s
    conductor->current = pShape; //points current to pShape point
    conductor->next = 0; //prevents loops from going out of bounds
}

void ShapeList::print()
{
    conductor = root; //the conductor points to the start of the linked list
    if(conductor != 0)
    {
        while(conductor->next != 0)
        {
            conductor = conductor->next;
            cout << conductor->current->width << endl;
        }
        //cout << conductor->current->width << endl;
    }
}

克隆函数在所有形状中都被重载,在这种情况下它是矩形的:

Rectangle * Rectangle::clone() const
{
    cout << "Rectangle's clone function called" << endl;
    Rectangle copiedRect(this);
    Rectangle * pCopiedRect = &copiedRect;
    return pCopiedRect;
}

Rectangle::Rectangle(const Rectangle *ref)
{
    cout << "Rectangle's copy constructor called" << endl;
    this->x = ref->x;
    this->y = ref->y;
    this->width = ref->width;
    this->height = ref->height;
}

我知道它很多,我很抱歉。如果不需要,我可以删除东西。如果您愿意,我也可以添加更多。

我已经阅读了Alex Allain关于链接列表的教程*以及其他几篇文章。如果有人有另一篇文章,或类似的东西,建议我全是耳朵。

1 个答案:

答案 0 :(得分:1)

Rectangle::clone()正在调用未定义的行为。您将返回自动变量copiedRect的地址,该函数会在函数终止后立即降低范围。

试试这个:

Rectangle * Rectangle::clone() const
{
    cout << "Rectangle's clone function called" << endl;
    return new Rectangle(*this);
}

您的副本甚至不需要实施。 Rectangle的所有成员都可以轻易复制。默认应该可以正常工作。

注意:我并没有真正花时间来剖析您的列表插入代码,但上面的肯定是需要解决的问题。