【发布时间】:2017-04-21 20:14:17
【问题描述】:
我正在尝试使用模板继承来实现一个数据结构,当我尝试插入一个元素时,它给出了以下错误:
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;
}
任何意见都会很有帮助。
【问题讨论】:
-
没有这样的类称为
Elem,这是编译器告诉你的。有一个内部类Elem,它是模板类的成员,但这与一个完全不相关的模板试图引用的Elem类无关。哦,你也应该get rid ofusing namespace std;and completely forget that it exists。仅仅因为模板类中有一个内部类并不意味着您可以直接从另一个类中引用它。 C++ 不能以这种方式工作。 -
请注意,您在
~Base()中进行安全销毁的尝试根本不安全,因为aux仍然指向已删除的对象。 -
@SamVarshavchik 你说得好像问题在于它是一个内部类。但是如果我们继承,这将是完全合法的,比如
Base<int>而不是Base<T>。 -
到目前为止你尝试了什么?
-
我认为
Elem未被识别为类型。限定它 (Base::Elem) 或声明别名。
标签: c++ templates inheritance