繁体   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