c++ - 不能引用派生模板类中的基类成员

标签 c++ templates inheritance

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> ,它工作正常。我的模板有问题吗?

最佳答案

你需要:

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

因为在派生自类模板的类模板的实现中, 基本模板的成员必须通过 this 指针或 具有基类资质。

关于c++ - 不能引用派生模板类中的基类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41682341/

相关文章:

c++ - 在 Visual Studio 2010 C/C++ 中, "Rescan Solution"操作的作用是什么?

c++ - 在 C++ 中读取 COM 端口,出现错误

javascript - 未捕获的类型错误 : undefined is not a function Backbone Template

c++ - 为什么派生类不能访问 protected 基类成员?

c# - 访问 Web 服务中的继承类

c++ - 在 C++ 中的类的每个函数调用之前运行代码

c++ - 如何优化 C++ avr 代码

string - 在模板字符串中求值

c++ - 如何使用数组的 boost 来计算凸包,而不是单独设置每个点?

c++ - 从派生类构造函数初始化 protected 数据成员