2017-01-16 49 views
1
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;} 
}; 

爲什麼說''數據'未在此範圍內聲明'Push?我怎樣才能解決這個問題?當我刪除每個template<T>時,它正常工作。我的模板有問題嗎?無法在衍生模板類中引用基類成員

回答

6

你需要:

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 
}; 

因爲從類模板派生的類模板的實現中,基本模板的 成員必須通過該指針或 與基礎類資格稱爲。

+0

非常感謝你。這是有益的:)))。再次感謝 –

+0

@DươngNguyênĐào歡迎來到Stackoverflow :)看到如何說「謝謝」上的SO [我應該怎麼做當有人回答我的問題?](http://stackoverflow.com/help/someone-answers) –

2

作爲除了@小李的回答,你可能會考慮使用使用聲明

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;} 
}; 

現在dataStack類變爲可用。

+0

:) )。有效 :)) 。非常感謝 。你是如此兄弟:)) –

相關問題