模板类未从另一个模板类继承受保护的变量
Template class not inheriting the protected variable from another Template class
我正在制作一个链表,它本质上是通用的,具有一些基本功能。然后我尝试创建另一个名为"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;
有关详细信息,请参阅此线程。
相关文章:
- 如何从其他结构访问受保护的结构变量
- 从模板化父类中的派生内部类访问受保护的成员变量
- C++中的受保护变量
- 如何影响派生类中受保护的基变量
- C++,如何创建线程限制/受保护的变量和函数
- 类的静态成员变量(受保护)的作用域
- 无法在受保护的类中显示变量
- 虚函数在受保护变量上触发编译错误
- 为什么我无法访问作为参数传递到函数中的基类的受保护成员变量?
- 访问受保护的变量 - 继承和子类的复杂情况
- 继承受保护的函数和公共变量C++时发生多重继承编译错误
- 将指针变量限制为类和子类:受保护不太有效
- 为什么可以从派生实例访问基类中的受保护变量
- C++继承:受保护的变量不可用
- 继承中使用的受保护变量
- 有没有办法从类外部声明一个受保护C++变量?
- 模板类未从另一个模板类继承受保护的变量
- 访问派生类 C++ 中的受保护变量
- 错误变量受保护
- 实现文件中的实例变量 — 私有与受保护