我有一个uni任务,其中必须实现一个单独链接列表,其中包含从名为Shape的公共抽象基类派生的不同对象。在C++中创建单向链表的一些指针
我会链接到GitHub的类实现:shapes.h,shapes.cpp。到目前为止,它由Shape
及其派生类Circle
组成。稍后还会有Rectangle
,Point
和Polygon
。
我现在应该实现这些不同种类形状的单独链接列表。到目前为止,我想出了下面的类原型为List
-class和Node
-class:
class Node
{
public:
Node() {}
friend class ShapeList;
private:
Shape* data;
Node* nextNode;
};
class ShapeList
{
public:
ShapeList(){head = NULL;}
void Append(Shape& inData);
private:
Node* head;
};
添加元素void Append(Shape& inData)
为ShapeList
-object应该能够从主在下面的风格被称为:
ShapeList list1;
list1.Append(Circle(5,5,5));
list1.Append(Rectangle(4, 10, 2, 4));
鉴于此信息,我该如何去实施void Append(Shape& inData)
?我尝试了几种不同的方法,但到目前为止还没有提出正确的解决方案。
参数Append
应该不是(Shape& inData)
也是完全可能的。
编辑:
我实现Append(Shape& inData)
但它只能有时:
Circle circle1;
ShapeList list1;
list1.Append(circle1);
但与
ShapeList list1;
list1.Append (Circle(5,5,5))
到目前为止,我Append()
- 实施如下所示:
void ShapeList::Append(Shape& inData)
{
//Create a new node
Node* newNode = new Node();
newNode->data=&inData;
newNode->nextNode=NULL;
//Create a temp pointer
Node *tmp = head;
if (tmp != NULL)
{
//Nodes already present in the list
//Traverse to the end of the list
while(tmp->nextNode != NULL)
tmp = tmp->nextNode;
tmp->nextNode=newNode;
}
else
head=newNode;
}
这对你们看起来好吗?
如果您从临时对象创建链接列表,您将遇到很大麻烦。您需要复制或在堆上创建它们。 – 2012-04-10 17:21:22
你试过的方法是什么?它们有什么问题?他们为什么不工作,为什么不知道他们为什么不工作不会导致你找到更好的解决方案? – Caleb 2012-04-10 17:23:40
我猜你手头的第一个问题是你是否真正理解栈和堆之间的问题(内存而不是数据结构)?这将是真正理解您的解决方案的首要关键。 – RageD 2012-04-10 17:28:04