C 链接列表实现
C++ linked list implementation
我正在从事一个分配工作,我被要求在C 中实现链接列表。到目前为止,除了我创建新列表时,一切都很好。在我的方法create_list()
中。在我为Field
分配内容和ID号并尝试调用GetNext()
后,我会发现一个错误说:Request for member 'GetNext()' in 'Node' which is a non-class type '*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 << ":tOccupiedn";
break;
default:
cout << "Field " << _SquareNum << ":tEmptyn";
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()
-这两个完全等效。
使用的一个很好的助记符是,您将尖型操作员与指针使用:)
声明中的no
Field *Node = new Field(SIZE, EMPTY);
节点是类型指针到字段。
如果您有指向课程的指针,并且要访问该类的成员,则修复程序很简单。
使用->
。 Node->GetNext() = Gameboard;
我认为您的代码还有其他错误,而且我认为即使使用此"修复",它也将起作用。可能您真正想要的是
Node->SetNext(Gameboard);
您正在调用Node.GetNext()
,但Node
是指指针。您需要使用->
操作员而不是.
操作员,例如Node->GetNext()
。
如果要设置为L值,则该函数必须返回参考值。您的代码需要一些更改:
// Get the next node in the linked list
Field& GetNext() { return *_Next; }
然后您可以将函数用作L值
Node->GetNext() = *Gameboard;
相关文章:
- 使用简单类型列表实现的指数编译时间.为什么
- 为什么在排序链表上的这种合并实现总是将两个列表都设置为 NULL,而只有一个应该设置一个列表?
- 如何理解C++中链表的自由列表实现?
- 嵌套列表,用于在 C++ 中实现邻接列表
- 单链接列表实现,规则为 3
- 如何使用列表/数组在C++中实现 Python "... not in ..."?
- 在给定的项目列表上实现搜索?
- 如何在C / C++中正确实现链接列表而不会使程序崩溃
- 可视化 如何实现 c++ 列表的运算符=?
- 使用邻接列表C++实现 Dijkstra
- 使用初始值设定项列表作为函数参数的类对象实现运算符 [] 的示例
- 如何实现列表:<T>:迭代器?
- C++如何实现列表的数组
- 使用unique_ptr<>实现列表?
- 使用配对模板实现列表模板
- 实现列表迭代器和运算符:--++*
- 如何使用 Win32/WTL 实现列表视图的缩放
- 使用std::experimental::optional来实现列表
- 使用堆栈类实现列表类
- 实现列表:在末尾添加一个节点