模板派生类无法访问基类成员变量问题求助
问题原因及解决方法
这是C++模板继承中典型的依赖基类成员查找问题:当派生类是模板类,且继承的基类依赖于模板参数(即Base<T>)时,编译器在模板定义的解析阶段(未实例化前),不会主动查找依赖基类的成员。直接写top会被当作未声明的标识符,因为此时编译器无法确定Base<T>中是否存在该成员。
三种解决方法:
通过
this->访问成员
在派生类成员函数中用this->top明确该成员属于当前对象的基类部分,让编译器延迟到实例化阶段再查找:template<class T> bool Derived<T>::doo(){ this->top++; return true; }显式指定基类作用域
直接通过Base<T>::top指定成员所属的基类:template<class T> bool Derived<T>::doo(){ Base<T>::top++; return true; }在派生类中添加
using声明
在Derived类的public/protected区域添加using Base<T>::top;,将基类成员引入派生类作用域,之后即可直接使用top:template<class T> class Derived: public Base<T>{ public: using Base<T>::top; // 引入基类成员 bool doo(void); }; template<class T> bool Derived<T>::doo(){ top++; return true; }
修改后完整可运行代码示例(以this->方法为例):
#include<iostream> #include<cstdio> #include<vector> #define MAX_SIZE 100 using namespace std; template<class T> class Base{ public: int top = 0; }; template<class T> class Derived: public Base<T>{ public: bool doo(void); }; template<class T> bool Derived<T>::doo(){ this->top++; return true; } int main(int argc, char* argv[]){ Derived<int> *obj = new Derived<int>; obj->doo(); return EXIT_SUCCESS; }
内容的提问来源于stack exchange,提问作者J Jeshwanth Reddy
相关产品推荐
相关产品推荐

