我正在尝试使用模板继承来实现数据结构,当我尝试插入元素时,它会出现以下错误:
pilha.h:15:21:错误:'Elem'之前的预期类型说明符
this-> topo = new Elem(dado);
以及与之相关的其他几个错误。
代码:
base.h
#ifndef __BASE_H_INCLUDED__
#define __BASE_H_INCLUDED__
#include <string>
#include <iostream>
using namespace std;
template <class T>
class Base {
protected:
class Elem;
public:
Base(){
tam = 0;
}
virtual ~Base(){
if (tam == 0) return;
for(Elem *aux = topo; aux != NULL; aux = aux->ant) {
Elem *aux2 = aux;
delete(aux2);
}
}
bool vazia(){
return tam == 0;
}
unsigned int tamanho(){
return tam;
}
virtual T retira() = 0;
virtual void imprime(){
if(tam == 0) {
cout << "A " << nome_da_classe << " esta vazia!" << endl;
return;
}
cout << "Impressao = ";
for(Elem *aux = topo; aux != 0; aux = aux->ant) {
cout << aux->dado << " ";
}
cout << endl;
}
T ver_topo(){
if (tam == 0) {
cout << "A " << nome_da_classe << " esta vazia!" << endl;
return 0;
}
return topo->dado;
}
protected:
int tam;
class Elem{
public:
T dado;
Elem *prox;
Elem *ant;
Elem(T d){
dado = d;
}
};
Elem *topo;
Elem *base;
string nome_da_classe;
};
#endif
base.cpp
#include "base.h"
pilha.h
#ifndef __PILHA_H_INCLUDED__
#define __PILHA_H_INCLUDED__
#include "base.h"
template <class T>
class Pilha : public Base<T> {
public:
Pilha(){
this->topo = nullptr;
this->nome_da_classe = "Pilha";
}
~Pilha(){}
void insere(T dado){
if (!this->tam) {
this->topo = new Elem(dado);
this->topo->ant = nullptr;
} else {
Elem *elem = new Elem(dado);
elem->ant = this->topo;
this->topo = elem;
}
this->tam++;
}
T retira(){
if (this->tam == 0) {
cout << "A "<< this->nome_da_classe << " esta vazia!" << endl;
return 0;
}
T aux = this->topo->dado;
Elem *aux2 = this->topo;
this->topo = this->topo->ant;
delete(aux2);
this->tam--;
return aux;
}
};
#endif
pilha.cpp
#include <iostream>
#include "base.h"
#include "pilha.h"
的main.cpp
#include <iostream>
#include "pilha.h"
using namespace std;
int main() {
Pilha<int> *b = new Pilha<int>();
b->imprime();
b->insere(5);
delete(b);
return 0;
}
任何意见都会非常有用。
答案 0 :(得分:0)
普通名称查找找不到依赖基类的成员(类型依赖于一个或多个模板参数的基类)。你需要拼出typename Base<T>::Elem
:
this->topo = new typename Base<T>::Elem(dado);