开发者

Creating a linked list of objects

开发者 https://www.devze.com 2023-02-18 08:20 出处:网络
I have a class assignment (read: no use of the STL) where I need to create a sorted linked list of objects, but I\'m not quite sure how to go about doing this.

I have a class assignment (read: no use of the STL) where I need to create a sorted linked list of objects, but I'm not quite sure how to go about doing this.

The class that I am using contains both integer and string members, but it is only one of these integer members that will be sorted. I currently have a fully functioning linked list template that will successfully run with integer data.

Now my problem lies in converting this to work with my class. When instantiating this linked list, a <Type> must be defined, in this case that type is Poster, after the class Poster that I am sorting. However, in the declaration of the linked list class, there is a declaration and definition of the class Node which reads

class Node
{
public:
    Type Element;
    Node *Next, *Previous;

    Node() : Next(NULL), Previous(NULL) {} // Default constructo开发者_运维问答r
    Node (Type Data, Node *PNode = NULL) : // Non-default constructor
        Element (Data),
        Next (PNode),
        Previous (PNode) {}
};

I'm unsure how this existing definition will work when the members of Poster are introduced when LinkedList<Poster> listOfPosters is declared. Should I replace the above definition of Node with the contents of class Poster, or will Type Element in the node be marked as a sort of catch-all container for the members of class Poster, so that members of Poster can be accessible via Element.GetMemberValue()?


Im guessing that the declaration of the LinkedList class looks something like

template<class Type>
class LinkedList
{ ... }

When the program that uses the linked list class (the main program) instantiates a LinkedList class like following

LinkedList<Poster> myLinkedList;

The compiler, at compile time, generates code from the template, and replaces all occurrences of "Type" with "Poster". Therefore, you dont need to change the linked-list or node class.


The Node.Element member will store a (by-value) copy of the Poster. There is no need to manually replace anything in the definition of Node; that's the whole point of C++ templates.

When you declare a LinkedList<Poster> object, the compiler will generate a new class and substitute all instances of the Type placeholder with Poster. This will automatically create an appropriate Node class inside the LinkedList<Poster> class that represents nodes which hold a Poster object.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号