C++ 模板類子類無法訪問父類成員

首先聲明問題:模板類子類無法訪問父類成員。在實現<<數據結構>>鄧俊輝版第四章時,遇到如下代碼時,怎樣都無法編譯通過。

#include"Vector.h"
template<typename T> class Stack:public Vector<T>
{
    void push(T const& e) { insert(size(), e); } 
    T pop() { return remove(size() - 1); } 
    T& top() { return (*this)[size() - 1]; } 
};

提示錯誤如下:

../include/Stack.h: In member function 'void Stack<T>::push(const T&)':
../include/Stack.h:4:41: error: there are no arguments to 'size' that depend on a template parameter, so a declaration of 'size' must be available [-fpermissive]
     void push(T const& e) { insert(size(), e); }
                                         ^
../include/Stack.h:4:41: note: (if you use '-fpermissive', G++ will accept your code, but allowing the use of an undeclared name is deprecated)

從提示錯誤中,可以發現Stack類無法訪問Vector類的size()。該如何解決這個問題呢?

方法一:添加this->

#include"Vector.h"
template<typename T> class Stack:public Vector<T>
{
    void push(T const& e) { this->insert(this->size(), e); } 
    T pop() { return this->remove(this->size() - 1); } 
    T& top() { return (*this)[this->size() - 1]; } 
};

方法二:添加父類名稱Vector<T>::(偷懶ing...

void push(T const& e) { Vector<T>::insert(Vector<T>::size(), e); } 

具體參考了下面幾篇博客和討論:

https://blog.csdn.net/sb985/article/details/79670881

https://www.zhihu.com/question/28139230

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章