【问题标题】:linked list operator overloading issue链表运算符重载问题
【发布时间】:2014-02-27 12:25:49
【问题描述】:

我尝试建立自己的链表类,但据我所知,= operator overloading. 存在问题,我们应该在重载赋值运算符时使用 const 参数,比如使用linked_list<T>& operator=( const linked_list<T>& a)。但是,编译器给了我错误,除非我把 linked_list<T>& a 代替。编译器将停在 if(this->head==a.front()),给我错误

11  error C2662: 'linked_list<T>::front' : cannot convert 'this' pointer from 'const linked_list<T>' to 'linked_list<T> &'

以下是详细信息。

#ifndef _LINKED_LIST_H_
#define _LINKED_LIST_H_
template <class T>
struct node
{
    T data;
    node<T>* next;
};
template <class T>
class linked_list
{
   private:
    node<T>* head;
   public:
    linked_list<T>();
    linked_list<T>(const linked_list<T>& a);
    ~linked_list<T>();
    linked_list<T>& operator=(const linked_list<T>& a);
    bool isEmpty();
    int size() const;
    void insert_front(T a);
    void insert_end(T a);
    void erase_end();
    void erase_front();
    void print() const;
    void erase(node<T>* a);
    node<T>*& front()
    {
        node<T>* ptr = new node<T>;
        ptr = head;
        return ptr;
    }
    void setFront(node<T>* a);
};
#endif
template <class T>
linked_list<T>& linked_list<T>::operator=(const linked_list<T>& a)
{
    if (this->head == a.front())  // the error mentioned happened here. however,
                                  // if no const in the parameter, it would be
                                  // no error
    {
        return *this;
    }
    while (head != nullptr) erase_front();
    node<T>* copy;
    copy = a.front();
    while (copy->next != nullptr)
    {
        insert_end(copy->data);
        copy = copy->next;
    }
    return *this;
}

有人可以帮忙吗?谢谢。

【问题讨论】:

    标签: c++ operator-overloading operator-keyword


    【解决方案1】:

    当访问器返回对拥有结构的引用时,实现两个版本通常是个好主意:一个是非常量版本并返回一个非常量引用,另一个是常量并返回一个常量引用。这样它就可以在变异和非变异上下文中使用。 front() 将是一个很好的候选人。

    尽管附带说明——您可能不想在公共linked_list 接口中公开您的nodes,尤其是对它们的非常量引用。这就是完全封装在类中的东西。

    【讨论】:

    • 感谢您的帮助。问题解决了,你能在旁注中解释更多吗?我如何完全封装在课堂上?我试图将结构定义放在类中,然后我得到了很多错误......
    • 他的意思是你本质上想要将T 类型的项目存储在一个列表中。作为外部消费者,您并不关心该列表需要一个内部“垫片”,例如 node 结构。因此,front() 应该返回 T&amp;,而不是 node&lt;T&gt;
    【解决方案2】:

    问题在于front() 不是 const 成员函数,而您正试图在 const 实例上调用它。

    【讨论】:

    • 问题已解决。现在我有 node*& front() & node*& front() const,两种方法!谢谢大声笑!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-23
    • 2014-04-14
    • 2010-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多