【发布时间】:2019-08-15 01:03:59
【问题描述】:
我试图在链表中的某个位置插入一个数字。但是我无法正常访问下一个指针,因为它是私有成员,并且必须使用 getNext 函数。我不确定如何用这个函数分配下一个指针,因为它给了我错误。
#pragma once
class IntListNode {
public:
IntListNode(int e, IntListNode *nextptr):
elem(e), next(nextptr) { }
int &getElement() {return elem;}
IntListNode *getNext() {return next;}
private:
int elem; // linked list element value
IntListNode *next; // next item in the list
};
这是我尝试过的代码,但我不断收到错误。
void IntegerList::AddAtPosition(int num, int placement)
{
IntListNode* temp1 = head;
IntListNode* temp2 = head;
temp1->getElement() = num;
if (placement == 0)
{
head = temp1;
}
else
{
for (int i = 0; i < placement - 2; i++)
{
temp2 = temp2->getNext();
}
temp1->getNext() = temp2->getNext();
temp2->getNext() = temp1;
//THe Lines getting errors
}
}
错误信息:
E0137 "表达式必须是可修改的左值"
【问题讨论】:
-
这些是程序中的文件
-
链接失效且并非对所有用户可用 如果问题需要链接中包含的信息才能理解,则链接内容必须在问题本身中。宁愿制作 minimal reproducible example 来用代码压倒人们。 minimal reproducible example 的真正美妙之处在于经过几轮分而治之制作minimal reproducible example,您通常会自己发现错误。
-
免费线索:你显然可以赋值给
getElement()的返回值。花点时间想想为什么,getElement()有什么特别之处,然后你就可以自己解决问题了。一直盯着getElement(),直到你弄明白为止。
标签: c++ list class pointers linked-list