gpt4 book ai didi

c++ - 在继承的情况下不在此范围内声明

转载 作者:行者123 更新时间:2023-11-30 02:48:14 24 4
gpt4 key购买 nike

我有一个文件 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;
}

我想实现一个 push()。但是,当我编译时,编译器说:

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 会起作用...

关于c++ - 在继承的情况下不在此范围内声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22163607/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com