簡體   English   中英

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 << ":\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() -這兩個是完全等效的。

一個好的記憶法是將尖指針運算符與指針一起使用:)

您正在調用Node.GetNext() ,但是Node是一個指針。 您需要使用->運算符而不是. 運算符,如Node->GetNext()

聲明中沒有

Field *Node = new Field(SIZE, EMPTY);

節點的類型為指向字段的指針

如果您有一個指向類的指針,並且想要使用->來訪問該類的成員,則修復很簡單。

Node->GetNext() = Gameboard;

我認為您的代碼還有其他錯誤,並且即使此“修復”也無法正常工作。 可能您真正想要的是

Node->SetNext(Gameboard);

如果要設置為左值,該函數必須返回參考值。 您的代碼需要一些更改:

// Get the next node in the linked list
Field& GetNext() { return *_Next; }

那么您可以將該函數用作左值

Node->GetNext() = *Gameboard; 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM