简体   繁体   中英

Can't refer to base-class member in derived template class

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM