【问题标题】:Sorted Linked List in C++C++中的排序链表
【发布时间】:2013-10-01 12:32:13
【问题描述】:

这是我的问题。

我有一个如下的链表类:

#include <iostream>
#include "List.h"
template <class Elem>
class LList : public List<Elem> { //List is a virtual base class
protected:

    Node <Elem> *head;
    Node <Elem> *fence;
    Node <Elem> *tail;

    int leftCount; 
    int rightCount;
    void init();
    void removeAll(); 

public:
    LList(); 
    ~LList();
    //Rest of methods overridden from List class
    //////
};

然后我有一个名为 SortedLList 的类,它继承自 LList,如下所示:

#include "LinkedList.h"
#include "Helper.h"
template <class Elem> 
class SortedLList : public LList<Elem> {
protected:

    Helper *helper;
public:

    SortedLList();
    ~SortedLList();
    bool insert(const Elem&); //Override insertion method from LList class
};

在SortedLList(SortledLList.cpp)的实现中:

#include "SortedLList.h"
template <class Elem>
SortedLList<Elem>::~SortedLList() {
    removeAll();
}

template <class Elem>
bool SortedLList<Elem>::insert(const Elem &_e) {
    fence = head;
    //Rest of Code..
}

我遇到一个编译器错误:使用未声明的标识符 removeAll()。栅栏和头指针也没有被识别。我做错了什么?

谢谢。

【问题讨论】:

  • 这是一个学术练习还是您有其他理由重新实现标准库?
  • 这是一个学术练习,我必须实现几乎所有我可能使用的功能
  • “他们看不到”是什么意思?建议您在实例化 SortedLList 并调用继承方法和编译器错误的位置发布代码。
  • “看不到”,你能 1. 给出给出错误的代码,2. 复制粘贴错误,3. 指出问题代码中的哪一行错误。
  • 您是否应该使用私有继承来实现“SortedLList 是根据 LList 实现的”?公共继承说'a SortedLList is a LList',因此适用于 LList 的每个方法都可以应用于 SortedLList;此外,您可以将对 SortedLList 的引用传递给期望 LList 的函数,它会正常工作。你确定这就是你要达到的目标吗?如果没有,您可能需要使用公共继承以外的其他东西。

标签: c++ list sorting linked-list


【解决方案1】:

因为您的类是一个模板,所以某些问题可能会使编译器感到困惑。您可能认为您的代码直截了当且易于理解,在这种情况下确实如此。旧的编译器过去会尽力猜测和编译这段代码。

但是,为了防止程序员依赖它,较新的编译器更加严格并且在所有版本的此类代码上都失败了。

您需要做的是在调用基类函数时使用this 指针。这使得通话清晰明了。这看起来像this-&gt;removeAll()

另一种选择是使用全名限定符,例如LList&lt;Elem&gt;::removeAll()。我更喜欢使用this,因为它更容易阅读。

【讨论】:

猜你喜欢
  • 2023-04-04
  • 1970-01-01
  • 2011-08-07
  • 2016-01-18
  • 2013-04-04
  • 2012-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多