C++ c++;带有标题类的链表类
我想实现带有标题类的单链表,但我也尝试将链表的信息和指针设置为私有,编译器会告诉我 赋值的左操作数需要左值 pred->Next()=temp->Next() 这个代码怎么了C++ c++;带有标题类的链表类,c++,linked-list,C++,Linked List,我想实现带有标题类的单链表,但我也尝试将链表的信息和指针设置为私有,编译器会告诉我 赋值的左操作数需要左值 pred->Next()=temp->Next() 这个代码怎么了 #include <iostream> using namespace std; class IntSLLNode{ private: int info; IntSLLNode * next; public:
#include <iostream>
using namespace std;
class IntSLLNode{
private:
int info;
IntSLLNode * next;
public:
IntSLLNode(){
next=0;
}
IntSLLNode(int el,IntSLLNode *ptr=0){
info=el;
next=ptr;
}
int Info(){return info;}
IntSLLNode * Next(){return next;}
};
IntSLLNode * head,* tail;//header structure
class IntSLList{
IntSLList(){
head=0; tail=0;
}
public:
void addToHead(const int&);
void addToTail(const int &);
int deleteFromHead();
int deleteFromTail();
void deleteNode(int&);
void listele();
};
void IntSLList::addToHead(const int &el){
head=new IntSLLNode(el,head);
if(tail==0)
tail=head;
}
void IntSLList::addToTail(const int &el){
if(tail==0){
head=tail=new IntSLLNode(el,head);
}
else{
tail->Next()=new IntSLLNode(el);
tail=tail->Next();
}
}
int IntSLList::deleteFromHead(){
if(head==0){
cout<<"No value such that";
return -1;
}
int el=head->Info();
IntSLLNode * temp=head;
if(head==tail){
head=tail=0;
}
else{
head=head->Next();
}
delete temp;
return el;
}
#包括
使用名称空间std;
类IntSLLNode{
私人:
国际信息;
IntSLLNode*下一步;
公众:
IntSLLNode(){
next=0;
}
IntSLLNode(intel,IntSLLNode*ptr=0){
info=el;
next=ptr;
}
int Info(){return Info;}
IntSLLNode*Next(){return Next;}
};
IntSLLNode*头,*尾//标题结构
类IntSLList{
IntSLList(){
头部=0;尾部=0;
}
公众:
无效添加头(常数和);
void addToTail(const int&);
int deleteFromHead();
int deleteFromTail();
void deleteNode(int&);
void listle();
};
void IntSLList::addToHead(const int&el){
头部=新的内部节点(el,头部);
如果(尾==0)
尾=头;
}
void IntSLList::addToTail(const int&el){
如果(尾==0){
头部=尾部=新的内部节点(el,头部);
}
否则{
tail->Next()=新的IntSLLNode(el);
tail=tail->Next();
}
}
int IntSLList::deleteFromHead(){
如果(头==0){
coutNext();
}
删除临时文件;
返回el;
}
赋值给函数/方法的返回值不会有任何用处。只能为函数返回的值的引用赋值
class IntSLLNode{
...
int& Info(){return info;}
IntSLLNode*& Next(){return next;}
};
但是,它会破坏该节点的封装,并允许任何外部代码错误地更改列表中节点的链接。就我个人而言,我会将整个node类隐藏到list类中,并提供方法来访问
Info()
值,以便在此文件之外进行编码。首先,您需要了解左值和右值之间的区别。简单地说,lvalue是可以赋值的(变量等),而rvalue是一个临时值(就像您在这里返回的值:IntSLLNode*Next(){return Next;}
)然后,通过尝试将某些内容分配给右值,您将得到一个错误。
作为这里的解决方案,您可以将
IntSLLNode*设置为next
public或在Next()函数中返回对此类成员的引用。Next()
返回指针的副本。只修改拷贝没有什么意义,编译器试图告诉你的是什么。我希望这不是生产代码,而你只是学习C++。此实现在许多方面都不如std::list
,因此它必须是一个学习工具,是吗?要更改私有数据,节点可以有一个Follow
或链接到重新排列指针的成员。你需要哪一个取决于你如何看待列表组织。@是的,我只是想学习C++,这是我第一次关于它的代码测试,但是现在我需要一个解决方案,而不是轻视抱歉,我不想成为恶意,但是我在生产中看到太多的C++代码,在这里和那里刮去一些纳秒是非常危险的。如果你是C++新手,那就是一个很好的练习,祝贺你。
class IntSLLNode{
...
int& Info(){return info;}
IntSLLNode*& Next(){return next;}
};