c++ - 模板类继承给出未知变量错误

标签 c++ templates inheritance

我创建了一个名为“list”的抽象类,我继承了“list”类来创建队列和堆栈。但是,当我尝试编译代码时,出现错误,指出“tail, head, next”无法识别或未知。

#include <iostream>
#include <cstdlib>

using namespace std;

template <typename T>
class list{
public:
    T data;
    list<T> * head;
    list<T> * tail;
    list<T> * next;
    list(){head = tail = next = NULL;}
    virtual ~list(){}
    virtual void store(T) = 0;
    virtual T retrieve() = 0;
};

// QUEUE
template <typename T>
class queue : public list<T>{
public:
    virtual void store(T);
    virtual T retrieve();
};

template <typename T>
void queue<T>::store(T d){
    list<T> * temp = new queue<T>;
    if (!temp) exit(EXIT_FAILURE);

    temp->data = d;
    temp->next = NULL;

    if(tail){
        tail->next = temp;
        tail = temp;
    }

    if(!head) head = tail = temp;

}

template <typename T>
T queue<T>::retrieve(){
    T i;
    list<T> * temp;

    i = head->data;
    temp = head;
    head = head->next;

    delete temp;

    return i;
}



// STACK
template <typename T>
class stack : public list<T>{
public:
    virtual void store(T i);
    virtual T retrieve();
};

template <typename T>
void stack<T>::store(T d){
    list<T> * temp = new stack<T>;
    if(!temp) exit(EXIT_FAILURE);

    temp->data = d;

    if (tail) temp->next = tail;
    tail = temp;
    if(!head) head = tail;

}

template <typename T>
T stack<T>::retrieve(){
    T i;
    list<T> * temp;

    i = tail->data;
    temp = tail;
    tail = tail->next;

    delete temp;

    return i;
}




int main(){

    queue<int> mylist;

    for(int i = 0; i < 10; i++)
        mylist.store(i);

    for(int i = 0; i < 10; i++)
            cout << mylist.retrieve() << endl;
}

我创建了一个名为“list”的抽象类,我继承了“list”类来创建队列和堆栈。但是当我尝试编译代码时,出现错误,指出“tail, head, next”无法识别或未知。

错误如下:

..\main.cpp: In member function 'virtual T stack<T>::retrieve()':
..\main.cpp:86:6: error: 'tail' was not declared in this scope

最佳答案

显式引用基类作用域来访问继承的成员变量:

if(list<T>::tail){
// ^^^^^^^^^
    list<T>::tail->next = temp;
 // ^^^^^^^^^
    list<T>::tail = temp;
 // ^^^^^^^^^
}

也可以通过this访问:

if(this->tail){
// ^^^^^^
    this->tail->next = temp;
 // ^^^^^^
    this->tail = temp;
 // ^^^^^^
}

关于c++ - 模板类继承给出未知变量错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41286213/

相关文章:

c++ - 为什么在 C/C++ 中可以多次包含一个 header ?

c++ - 编写一个可以打开和使用另一个程序的程序 : (Audio program)

templates - 如果标签名称中包含 ".",我如何获取 Docker 镜像的标签?

c# - vtables是如何在c++和c#中实现的?

c++ - Directx 11 与 C++ : Difference between using constant buffers and SetRawValue()?

c++程序无法编译

c# - 仅返回类型不同的 C++ 多个接口(interface)?

python - 如何以自定义方式呈现 CheckboxGroup(或任何其他元素)?

c++ - 指针拷贝的虚拟方法不起作用

c# - 将 Collection<Derived> 转换为 Collection<Base>