我是 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/