【问题标题】:How to Access Members in a Linked List Inside a Linked List如何访问链接列表内的链接列表中的成员
【发布时间】:2019-04-27 01:21:57
【问题描述】:

我需要访问链表内的链表类的成员。我可以管理我的Artist 列表,但不能在我的SongList 类中设置int x。我试过用*(temp->songHead).x = 5;、*temp->songHead.x = 5;、*(temp->songHead)->x = 5; 和*temp->songHead->x = 5; 设置它。

当我编译它时,我得到了错误:

不完整类型'struct songList'的无效使用

如何设置 int x?

#ifndef LINKED_LIST
#define LINKED_LIST
class SongList{
    public:
        SongList();
        int x;
        void add(int x);
    private:
        struct Song{
            char *name;
            int minutes;
            int seconds;
            int views;
            int likes;
            Song *next;
        };
        Song *head;
};

class LinkedList{
    public:
        LinkedList();
        ~LinkedList();

        void test(int x);
        void add(char ch);
        bool find(char ch);
        bool del(char ch);
        void list();

    private:
        struct Artist{
            char character;
            Artist *next;
            struct songList *songHead;
            SongList ptr;
        };
        Artist *head;
};
#endif

// Code to set int x
void LinkedList::test(int x){
    struct Artist *temp;
    temp = head;
    *(temp->songHead).x = 5;
}

【问题讨论】:

  • 为什么使用手动链表而不是std::list?填充列表的代码在哪里?在test() 中,假设songList 不为空(你不检查),你不需要使用operator* 来访问x,你可以使用operator-> 代替:head->songHead->x = 5;
  • struct songList *songHead; 没有songList 你是说SongList吗?
  • 这是一个学校作业,我知道该类存在 b/c 我在构造函数中对其进行了测试,我没有测试任何现有节点,但我不需要任何设置诠释 x。
  • 从变量声明中删除 struct,在 c++ 中是不必要的,并且隐藏了问题的原因

标签: c++ class pointers data-structures linked-list


【解决方案1】:

C++ 不要求您在包含structs 的变量声明前添加struct。添加它允许您在变量声明中使用未定义的类型。

如果您删除 struct,您将很快看到错误的真正原因:

songList *songHead;

会给出类似这样的错误(这是来自 clang,其他编译器可能没有那么有用):

错误:未知类型名称'songList';您是说“SongList”吗?

您对songHead的访问也不正确:

*(temp->songHead).x = 5;

这相当于:

*(temp->songHead.x) = 5;

你真正想要的是:

(*temp->songHead).x = 5;

或者更简单地说:

temp->songHead->x = 5;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-26
    相关资源
    最近更新 更多