Reputation: 26
template <class T>class Array
{
protected :
T* data;
int size;
};
template<class T>class Stack : protected Array<T>
{
int top;
public:
Stack(){};
public:
void Push(T x) {data[++top] = x;}
};
Why it say '"data" was not declared in this scope' in Push
? How can I fix this? When I delete each template<T>
, it works normally. Is something wrong in my template?
Upvotes: 1
Views: 320
Reputation: 17483
As an addition to @Mike's answer you might consider using using declaration:
template <class T>class Array
{
protected :
T* data;
int size;
};
template<class T>class Stack : protected Array<T>
{
using Array<T>::data; // <--- HERE
int top;
public:
Stack(){};
public:
void Push(T x) {data[++top] = x;}
};
Now data
becomes available in Stack
class.
Upvotes: 2
Reputation: 61417
You need:
template <class T>class Array
{
protected :
T* data;
int size;
};
template<class T>class Stack : protected Array<T>
{
int top;
public:
Stack(){};
public:
// void Push(T x) {data[++top] = x;} <-- Won't compile
void Push(T x) {this->data[++top] = x;} // <-- Will compile
// void Push(T x) {Array<T>::data[++top] = x;} <-- Will also compile
};
Because within the implementation of a class template derived from a class template, members of the base template must be referred to via the this pointer or with base-class qualification.
Upvotes: 7