模板类不从另一个Template类继承受保护的变量

时间:2014-12-06 21:29:35

标签: c++ templates linked-list set

我正在制作一个链接列表,它本质上是通用的并且具有一些基本功能。然后我试图创建另一个名为“Set”的模板类,它继承自LinkedList。但是当我尝试访问“head”时,它是在链接列表中定义的Node<> *。它给出了一个错误。我的文件是:

LinkedList.h

template <typename T>
struct Node {
        T data;
        Node<T> *next;
};

template <typename T>
class LinkedList {
public:
        Node<T>* head;
        int size;

        LinkedList();
        LinkedList(const LinkedList<T> &lst);
        ~LinkedList();

        Node<T>* getHead();
        Node<T>* getTail();
};

template <typename T>
class Set:public LinkedList<T> {
public:
        void insert(T item);
        friend ostream&(ostream& out, const Set<T> set)
};

并且insert的实现是:

template <typename T>
void Set<T>::insert(T item) {
       Node<T>* temp = head;
       bool present = false;

       while (temp != NULL) {
                if (temp->data == item) {
                        present = true;
                }

                temp = temp->next;
       }

        if (present == false) {
                /*Node<T> *tail = getTail();
                Node<T>* newTail = new Node<T>(item);
                newTail->next = NULL;
                tail->next = newTail;*/
        }
}

它说:

  

error: "head" was not declared in this scope in line "Node<T>* temp = head"

2 个答案:

答案 0 :(得分:3)

这个C ++的奇怪之处在于两阶段查找以及head是一个从属名称(作为基类的成员,依赖于&#34;当前&#34;类&#39; s模板参数):

  

[C++11: 14.6.2/3]:在类或类模板的定义中,如果基类依赖于模板参数,则在定义类模板时,在非限定名称查找期间不会检查基类作用域或成员或在类模板或成员的实例化期间。 [..]

通过将this引入表达式(每[C++11: 3.4.5])来绕过非限定查找:

Node<T>* temp = this->head;
//              ^^^^^^

对此之前的Stack Overflow答案有更长的解释:


这是一个最小(ish)测试用例:

#include <iostream>

template <typename T>
struct Base
{
    int x = 42;
};

template <typename T>
struct Derived : Base<T>
{
    void foo();
};

template <typename T>
void Derived<T>::foo()
{
    std::cout << x << '\n';
}

int main()
{
    Derived<void> d;
    d.foo();
}
// main.cpp: In member function 'void Derived<T>::foo()':
// main.cpp:18:18: error: 'x' was not declared in this scope
//      std::cout << x << '\n';
//                   ^

live demo

要修复,请更改foo

template <typename T>
void Derived<T>::foo()
{
    std::cout << this->x << '\n';
}

live demo

答案 1 :(得分:2)

您继承自依赖的基类,因此需要使用this限定成员访问权限:

Node<T>* temp = this->head;

有关详细信息,请参阅this thread

相关问题