我正在做一项作业,要求我用 C++ 实现链表。到目前为止,除了我创建新列表时,一切都很好。在我的方法 create_list()
中。在我为我的 Field
分配内容和 ID 号并尝试调用 GetNext()
后,我收到一条错误消息:Request for member 'GetNext()' in “Node”是一个非类类型“*Field”。
我对 C++ 语法和面向对象编程还是很陌生。我究竟做错了什么?我认为通过使用行 Field *Node = new Field(SIZE, EMPTY);
我的变量 Node
将属于类类型 Field
。 ..?
#include <iostream>
#include <ctype.h>
using namespace std;
typedef enum { EMPTY, OCCUPIED } FIELDTYPE;
// Gameboard Size
int SIZE;
class Field {
private:
int _SquareNum;
FIELDTYPE _Content;
Field* _Next;
public:
// Constructor
Field() { }
// Overload Constructor
Field(int SquareNum, FIELDTYPE Entry) { _SquareNum = SquareNum; _Content = Entry; }
// Get the next node in the linked list
Field* GetNext() { return _Next; }
// Set the next node in the linked list
void SetNext(Field *Next) { _Next = Next; }
// Get the content within the linked list
FIELDTYPE GetContent() { return _Content; }
// Set the content in the linked list
void SetContent(FIELDTYPE Content) { _Content = Content; }
// Get square / location
int GetLocation() { return _SquareNum; }
// Print the content
void Print() {
switch (_Content) {
case OCCUPIED:
cout << "Field " << _SquareNum << ":\tOccupied\n";
break;
default:
cout << "Field " << _SquareNum << ":\tEmpty\n";
break;
}
}
}*Gameboard;
这是我的 create_list() 方法:
void create_list()
{
int Element;
cout << "Enter the size of the board: ";
cin >> SIZE;
for(Element = SIZE; Element > 0; Element--){
Field *Node = new Field(SIZE, EMPTY);
Node.GetNext() = Gameboard; // line where the error is
Gameboard = Node;
}
}
最佳答案
.
用于寻址对象中的成员和对对象的引用。然而,Node
是指向对象的指针。所以你需要把它变成一个引用,然后你才能使用它与.
。这意味着执行 (*Node).GetNext()
。或者您可以使用简写:Node->GetNext()
- 这两个完全等价。
一个很好的助记符是使用带指针的尖运算符:)
关于C++链表实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13171955/