我有一个任务,要求我将对象添加到链表中。所讨论的对象是形状。
我的问题是我可以向列表中添加对象,但是当我尝试打印它们时,只有最后添加的对象被打印出来,其余的只是垃圾值。
我的代码是这样的:
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;
}
}
clone函数在所有形状中都是重载的,在本例中是矩形的:
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关于链表的教程*,以及其他一些文章。如果有人有其他文章,或者类似的东西,我洗耳恭听。
- http://www.cprogramming.com/tutorial/c/lesson15.html
Rectangle::clone()
正在调用未定义行为。您正在返回一个自动变量copiedRect
的地址,该变量在函数终止后立即脱离作用域。
试试这个:
Rectangle * Rectangle::clone() const
{
cout << "Rectangle's clone function called" << endl;
return new Rectangle(*this);
}
你的复制器甚至不应该被实现。Rectangle
的所有成员都是可复制的。默认值应该可以正常工作。
注意:我没有真正花时间仔细分析列表插入代码,但上面的绝对是需要解决的问题。