2012-11-01 62 views
0

我正在做一个任务,我被要求在C++中实现链表。到目前为止,除了当我创建一个新列表时,一切都很好。在我的方法create_list()。在将内容和身份号码分配给我的Field并尝试拨打GetNext()后,我收到一条错误消息:Request for member 'GetNext()' in 'Node' which is a non-class type '*Field'.我对C++语法和面向对象编程还不熟悉。我究竟做错了什么?我想通过使用行Field *Node = new Field(SIZE, EMPTY);我的变量Node将是类型Field ...?C++链表实现

#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; 
    } 
} 

回答

1

没有在声明

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

节点的类型是指针还田。

如果您有一个指向某个类的指针,并且您想访问该类的成员使用->,修正很简单。

Node->GetNext() = Gameboard; 

我认为你的代码有其他错误,我不认为即使这个'修复'它会工作。可能你真正想要的是

Node->SetNext(Gameboard); 
+0

真棒谢谢....现在,我真的觉得它更有意义.... – accraze

1

你打电话Node.GetNext(),但Node是一个指针。您需要使用->运营商,而不是.运营商,如Node->GetNext()

+0

试过,但现在我得到这个错误:“需要左值作为转让的左操作数” – accraze

+0

@SunHypnotic看到我的答案。 – john

3

.用于寻址对象中的成员和对象的引用。然而,Node指向的一个对象。所以你需要把它变成一个参考,然后才能和.一起使用它。这意味着要做(*Node).GetNext()。或者您可以使用简写:Node->GetNext() - 这两个完全相同。

一个很好的记忆使用的是您使用指针尖尖的操作:)

0

如果你想设置为l值,函数必须返回一个参考值。 你的代码需要一些变化:

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

那么你可以使用该功能作为一个左值

Node->GetNext() = *Gameboard;