c++ - 无法在 Main.cpp 中使用链表

标签 c++ linked-list

我是 C++ 新手,有 C# 背景。我正在尝试使用链表进行练习。

我遇到的问题是我正在尝试使用我创建的以下链表:

class Board {
typedef struct BoardList{
        Board b_data;
        Node *next;
    }* boardPtr;

    boardPtr head;
    boardPtr current;
    boardPtr temp;

}

现在我正尝试在我的主要方法中“实例化”它,但我不确定如何完成它。这是我在网上研究和发现的,但它仍然不起作用-

int main(){

BoardList* first = NULL; //first element will be added after a board object is added to the list that's why i left this as null

}

但我不断收到“无法解析类型 BoardList”错误。我在我的 IDE 中使用 CLion。

最佳答案

您不必使用 typedef 关键字在 C++ 中声明新结构。要声明 BoardList 指针类型,请使用 typedef 关键字。试试这个代码:

class Board {
    struct BoardList{
        Board b_data;
        Node* next;
    };
    using BoardList* boardPtr;

    boardPtr head;
    boardPtr current;
    boardPtr temp;
}

对于主要部分 - BoardList 仅在类 Board 中可用,因为它在此类的私有(private)部分中定义。如果你想在 Board 类之外使用这个结构,你有一些选择:

在类 Board 的公共(public)部分声明 BoardList

class Board {
public:
    struct BoardList{
        Board b_data;
        BoardList* next;
    };

private:
    ....
};

int main() {
    Board::BoardList* first = NULL;
    return 0;
}

Board类之上声明BoardList

class Board; // Pay attention! Forward declaration is required here!

struct BoardList{
    Board *b_data; // Pay attention! You have to use pointer in this case because it is defined above the class. You can declare it under the class as I will show in the next section. 
    BoardList *next;
};

class Board {
    typedef BoardList* boardPtr;

    boardPtr head;
    boardPtr current;
    boardPtr temp;

};

int main(){

    BoardList* first = NULL;

    return 0;
}

在类Board下声明BoardList

struct BoardList; // Pay attention! Forward declaration is required here!

class Board {
    typedef BoardList* boardPtr;

    boardPtr head;
    boardPtr current;
    boardPtr temp;

};

struct BoardList{
    Board *b_data;
    BoardList *next;
};

int main(){

    BoardList* first = NULL;

    return 0;
}

关于c++ - 无法在 Main.cpp 中使用链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51757173/

相关文章:

c# - 从 LinkedList<> 中删除项目

c++ - 添加新节点时,链表节点尾部不更新

对指针的更改不是永久性的

c++ - 嵌套的 if 语句 C++

c# - C++ 与 C# 相比,计算速度提高了 15 倍,这是合法的吗?

c++ - <未解析的重载函数类型>

c++ - 避免在 C++ 中产生僵尸进程

c++ - 如何在编译时交换可变参数模板的两个参数?

c - 按值对链表进行排序 -

c - 在链表中,最后一个节点->下一个不为NULL,导致段错误