无法使用Main.cpp中的链接列表

时间:2018-08-09 00:01:39

标签: 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类型”错误。我正在将CLion用于我的IDE。

2 个答案:

答案 0 :(得分:1)

您不必使用typedef关键字就可以在c ++中声明新的结构。要声明BoardList指针类型,请使用typedef关键字。尝试以下代码:

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

    boardPtr head;
    boardPtr current;
    boardPtr temp;
}

对于主要部分,BoardList仅在类Board中可用,因为它在此类的私有部分中定义。如果要在类Board之外使用此结构,则可以选择以下选项:

在类BoardList的公共部分声明Board

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

private:
    ....
};

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

在课程BoardList上方声明Board

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;
}

在类BoardList下声明Board

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;
}

答案 1 :(得分:0)

问题1:

Boardlist是内部类型,因此您需要在Board ::

前面加上前缀

问题2

董事会列表是私有定义的,应该公开。

带更正的代码:

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

    boardPtr head;
    boardPtr current;
    boardPtr temp;

}

int main(){

Board::BoardList* first = NULL; 

}