C 链接列表实现

C++ linked list implementation

本文关键字:实现 列表 链接      更新时间:2023-10-16

我正在从事一个分配工作,我被要求在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;