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



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

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

插入的实现是:

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"

这种C++奇怪是由于两阶段查找以及head是一个依赖名称的事实(作为依赖于"当前"类的模板参数的基类的成员):

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

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

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

关于之前的堆栈溢出答案,有一个更长的解释:

  • 为什么必须通过 this 指针访问模板基类成员?

这是一个最小的测试用例:

#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';
//                   ^

(现场演示)

要修复,请更改foo

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

(现场演示)

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

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

有关详细信息,请参阅此线程。

最新更新