【问题标题】:Linked List with data type of a struct具有结构数据类型的链表
【发布时间】:2014-03-04 17:30:59
【问题描述】:

如何在 main 中声明具有结构数据类型的链表实例? 例如......我应该有一个带有保存信息的结构的类。链表应该具有结构的数据类型。指令如下:DVD 类具有结构,其数据成员之一是以该结构为数据类型的链表实例。

class DVD
{
private:
struct disc
{
int length;
string name;
};

链表

template <class T>
class LinkedList1 
{
private:
// Declare a structure
struct discList
{
    T value;
    struct discList *next;  // To point to the next node
};

discList *head;     // List head pointer

public:
// Default Constructor
LinkedList1()
{ head = NULL; }


// Destructor
~LinkedList1();

// Linked list operations
void appendNode(T);
void insertNode(T);
void deleteNode(T);
void displayList() const;
};

【问题讨论】:

    标签: c++ struct linked-list declaration


    【解决方案1】:

    您所要做的就是在尖括号之间指定类型,如下所示:
    LinkedList1&lt;DVD&gt; myLinkedList;

    编辑:

    这是幕后发生的事情,编译器会将每个T 替换为DVD。

    回到你的代码,我们得到这个:

    struct discList
    {
        DVD value; // You used to have T here
        struct discList *next;  // To point to the next node
    };
    

    您将拥有一个链表,其中每个节点都是一个包含DVD 值的结构。

    【讨论】:

    • 我知道LinkedList1&lt;DVD&gt; myLinkedList; 将导致类DVD 成为链表的数据类型,但我需要结构disc 成为链表的数据类型。还是因为struct disc 是class DVD 的一部分,LinkedList1&lt;DVD&gt; myLinkedList; 才会起作用?其他人告诉我公开我的结构。我不在家测试它。
    • 指令如下:DVD类具有结构,其数据成员之一是以该结构为数据类型的链表实例。
    • 谢谢。澄清很好。这就是我的方式,但我猜“以结构作为数据类型”的指令让我失望。赞成票
    【解决方案2】:

    模板类应该可以访问结构的名称。

    您可以单独定义此结构,并在 DVD 类中同时使用它的定义,并作为模板类的模板参数,例如

    struct disc
    {
    int length;
    string name;
    };
    
    
    class DVD
    {
    private:
       disc obj;
    };
    

    然后

    LinkedList<disc> l;
    

    或者您可以为 DVD 类中的结构光盘定义一个公共 typedef。例如

    class DVD
    {
    private:
    struct disc
    {
    int length;
    string name;
    };
    public:
      typedef disc disc_t;
    };
    
    
    LinkedList<DVD::disc_t> l;
    

    【讨论】:

      猜你喜欢
      • 2016-07-30
      • 1970-01-01
      • 1970-01-01
      • 2019-01-08
      • 1970-01-01
      • 2021-11-13
      • 2017-07-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多