我目前正在为我在学校修读的类(class)学习一些 C++。我对左值和右值有基本的了解,但我无法确定为什么会收到编译器错误。
我正在创建一个单向链表并且需要能够反转它。根据我的任务,我有两个类(class)。第一个是节点,它只包含一个整数和一个指针。
class Node {
int data;
Node *next;
public:
//Constructor
Node(int d) {
data = d;
next = NULL;}
//Set to next Node
void SetNext(Node *nextOne) {
next = nextOne;}
//Returns data value
int Data(){return data;}
//Returns next Node
Node *Next() {return next;}
};
然后我有一个链表类,它有一个标题指针,然后是一些用于添加、打印等列表的函数。
class LinkedList {
Node *head;
public:
//Constructor
LinkedList(){head = NULL;}
void AddNode(int d) {
//Create a new Node
Node *newNode = new Node(d);
//Create a temporary pointer
Node *temp = head;
//If there are already nodes in the list
if(temp != NULL) {
//Parse through to the end of the list
while(temp->Next() != NULL) {
temp = temp->Next();}
//Point the last Node in the list to the new Node
temp->SetNext(newNode);
}
//If adding as the first Node
else{
head = newNode;}
}
void PrintList() {
//Temporary pointer
Node *temp = head;
//If there are no nodes in the list
if(temp == NULL) {
std::cout << "The list is empty" << std::endl;}
//If there is only one node in the list
if(temp->Next() == NULL) {
std::cout << temp->Data() << std::endl;}
//Parse through the list and print
else {
do {
std::cout << temp->Data();
temp = temp->Next();
}
while(temp != NULL);
}
}
//Returns the number of nodes in the list
int CountList() {
//Temporary pointer
Node *temp = head;
//Counter variable
int counter = 0;
//If the list is empty
if(temp == NULL) {
return counter;}
//Parse through Nodes counting them
else {
do {counter++;
temp = temp->Next();
}
while(temp != NULL);
}
return counter;
}
//Reverses the list
Node *ReverseList() {
//Initially set to NULL then tracks the new head
Node *marker = NULL;
//Tracks the next one in the list
Node *nextOne;
//Sets the first Node to NULL and then sets the last Node to point to
//the first one and rotates through the list pointing the last to the
//first
while(head != NULL) {
nextOne = head->Next();
head->Next() = marker;
marker = head;
head = nextOne;
}
//Setting the head back to the start again
head = marker;
}
};
其中一个函数应该反转列表。 “head->Next() = marker;”这一行在 ReverseList 函数中导致编译时出现“需要左值作为赋值的左操作数”错误。
关于为什么会发生这种情况以及如何解决问题的任何见解?
提前致谢!
最佳答案
调用 Next()
的返回值是一个右值。由于您在类函数中,因此无需调用 Next
函数来获取私有(private) next
指针,您可以直接使用它。
head->next = marker;
关于c++ - "lvalue required as left operand of assignment"写链表错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32929796/