У меня есть задание, которое требует от меня добавления объектов в связанный список. Объектами, о которых идет речь, являются фигуры.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();
}
Я не разрешено изменять этот код. Например, мне не разрешено отправлять указатель на новый прямоугольник, я должен «глубоко копировать» его. (Я надеюсь, что я использую это слово правильно.)
Мой 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;
}
Я знаю, что много читать, и мне очень жаль. Я могу удалить материал, если он не нужен. Я также могу добавить больше, если вы захотите.
Я прочитал учебник Алекса Аллена * о связанных списках и еще несколько других статей. Если у кого-то есть другая статья или что-то в этом роде, чтобы предложить мне все уши.