我一直在尝试使用模板来实现堆栈。我的问题是在这种情况下如何使用父类中的变量?
在这种情况下,我的编译错误是:“top, a, size”未在此范围内声明。
template<class T>
class buffer
{
public:
T *a;
int top,i,size;
};
template<class T>
class Queue: public buffer<T>
{
public:
Queue(int siz)
{
a=new T[siz];
size=siz;
top=-1;
}
void push(T ele)
{
if(top!=size-1){a[++top]=ele;}
}
T pop()
{
return(a[top--]);
}
void print()
{
for(i=0;i<top;i++)
cout<<" "<<a[i];
cout<<endl;
}
};
最佳答案
要使它们成为从属名称,您必须使用 this->
或buffer<T>::
之前。
所以
this->a = new T[siz];
this->size = siz;
this->top = -1;
关于c++ - 使用父类的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34387834/