【问题标题】:c++ linked list class with header classc++链表类与头类
【发布时间】:2017-10-08 11:59:50
【问题描述】:

我想用头类实现单链表,但我也在尝试将链表的信息和指针设为私有,编译器告诉我

需要左值作为赋值的左操作数 pred->Next()=temp->Next();

这段代码有什么问题?

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

【问题讨论】:

  • Next() 返回指针的副本。只修改副本没有多大意义,这是编译器试图告诉你的。
  • 我希望这不是生产代码,而您只是在学习 C++。这个实现在很多方面都不如std::list,它必须是一个学习工具,是吗?
  • 要更改私有数据,Node 可以有一个重新排列指针的FollowLinkTo 成员。您需要哪一个取决于您如何看待列表的组织方式。
  • @wigy 是的,我只是想学习 C++,这是我的第一个代码测试,但现在我需要一个解决方案而不是蔑视
  • 抱歉,我不想刻薄,但我在生产环境中看到了太多的 C++ 代码,这真的很危险,以至于在这里和那里减少一些纳秒。如果您是 C++ 新手,那么您正在做的事情是一个很好的练习,恭喜。

标签: c++ linked-list


【解决方案1】:

首先,你需要了解左值和右值的区别。简单来说,lvalue 是可以赋值的东西(变量等),而 rvalue 是一个临时值(就像您在此处返回的值一样:
IntSLLNode * Next(){return next;})
然后,通过尝试将某些内容分配给右值,您会得到一个错误。
作为这里的解决方案,您可以公开您的 IntSLLNode * next; 或在 Next() 函数中返回对此类成员的引用。

【讨论】:

    【解决方案2】:

    分配给函数/方法的返回不会做任何有用的事情。您只能分配给函数返回值的引用

    class IntSLLNode{
        ...
        int& Info(){return info;}
        IntSLLNode*& Next(){return next;}
    };
    

    但是,它会破坏该节点的封装,并允许任何外部代码错误地更改列表中节点的链接。就个人而言,我会将整个节点类隐藏到列表类中,并提供访问Info() 值的方法以在此文件之外进行代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-02
      • 2012-01-28
      • 1970-01-01
      相关资源
      最近更新 更多