在继承的情况下未在此范围内声明
问题描述:
我有一个文件my_node.h
。在这个文件中,我宣布一个Stack类:在继承的情况下未在此范围内声明
template<class Datatype>
class Stack
{
public:
Stack() : head(NULL)
{
}
virtual ~Stack()
{
Datatype temp;
while (pop(temp));
cout << "Stack released all spaces" << endl;
}
public:
virtual int push(Datatype &);
virtual int pop(Datatype &);
virtual Datatype* peek();
protected:
Node<Datatype> *head;
};
然后,我有一个名为new_stack.h另一个文件。在这个文件中,我写了一个Stack的继承类,它是StackWithDeep。代码如下所示:
#include "my_node.h"
#include <iostream>
#include <list>
using namespace std;
template<class Datatype>
class StackWithDeep : public Stack<Datatype>
{
public:
StackWithDeep(int thre) : Stack<Datatype>()
{
stack_deep = 0;
limited_deep = thre;
}
virtual ~StackWithDeep()
{
}
public:
virtual int push(Datatype &);
virtual int pop(Datatype &);
int getdeep()
{
return stack_deep;
}
private:
int stack_deep;
int limited_deep;
};
template<class Datatype>
int StackWithDeep<Datatype>::push(Datatype &new_data)
{
Node<Datatype> *pt_node = new Node<Datatype>;
if (pt_node == NULL)
return -1;
if (stack_deep != limited_deep)
{
pt_node -> addData(new_data);
if (head == NULL)
head = pt_node;
else
{
pt_node -> addPrev(*head);
head = pt_node;
}
stack_deep ++;
return 1;
}
else
{
delete pt_node;
return 0;
}
return 0;
}
我想实现按键()。然而,当我编译,编译器说:
In member function ‘virtual int StackWithDeep<Datatype>::push(Datatype&)’:
error: ‘head’ was not declared in this scope
我想我可以用这个head
指针,因为它在Stack类保护,我的新的类继承做公开。
答
Standard says that unqualified names in a template are generally
non-dependent and must be looked up when the template is defined.
Since the definition of a dependent base class is not known at that
time (there may be specialisations of the base class template that
have not yet been seen), unqualified names are never resolved to
members of the dependent base class. Where names in the template are
supposed to refer to base class members or to indirect base classes,
they can either be made dependent by qualifying them or brought into
the template's scope with a using-declaration
使用this->head
,将工作...
答
您的代码流在VS2012中正常工作。但在Ideone.com失败。
如果您在派生类中使用头,那么使用基类对其进行限定,如下所示:Stack<Datatype>::head
。这对我有效。