我想创建一个模板向量,但是当我返回迭代器时会出现问题。 我一直在搜索所有互联网,但没有找到任何解决方案。 这是代码:
template <class Element>
class VectorDinamic {
public:
VectorDinamic();
void add(Element el);
Element get(int poz);
~VectorDinamic();
void update(Element el,int poz);
int len();
//template <class Element>
//I get errors here: missing type specifier, unexpected token precedin ";" , missing ";" before "<"
vectorDinamicIterator<Element>* iterator();
void del(Element el);
private:
Element* elems;
int lg;
int capacitate;
void resize();
};
template <class Element>
class vectorDinamicIterator{
public:
vectorDinamicIterator(VectorDinamic* vect){
this->curent=0;
this->vec = vect;
}
Element element()
{
return vec->get(this->curent);
}
void next(){
curent++;
}
private:
int curent;
VectorDinamic* vec;
};
template <class Element>
VectorDinamic<Element>::VectorDinamic() {
capacitate = INIT_CAPACITY;
elems = new Element[capacitate];
lg = 0;
}
//I get errors down here: iterator is not a member of VectorDinamic<Element>,
template <class Element>
vectorDinamicIterator<Element>* VectorDinamic<Element>::iterator()
{
vectorDinamicIterator iter = new vectorDinamicIterator(this);
return iter;
}
我遗漏了一些方法实现以保持代码简短,我在错误中添加了注释,我不知道为什么。没有“迭代器”方法,代码工作得很好。
答案 0 :(得分:2)
您错过了vectorDinamicIterator
的(转发)声明。每个名字在使用前都必须声明。
template < class Element >
class vectorDinamicIterator;
template <class Element>
class VectorDinamic {
public:
VectorDinamic();
void add(Element el);
Element get(int poz);
~VectorDinamic();
void update(Element el,int poz);
int len();
vectorDinamicIterator<Element>* iterator(); // <- name must be known
void del(Element el);
private:
Element* elems;
int lg;
int capacitate;
void resize();
};
template <class Element>
class vectorDinamicIterator{
public:
typedef VectorDynamic<Element> Vector; //<---- specify template argument!
vectorDinamicIterator(Vector* vect){
this->curent=0;
this->vec = vect;
}
Element element()
{
return vec->get(this->curent);
}
void next(){
curent++;
}
private:
int curent;
Vector* vec;
};
Yam Marcovic是对的,您还需要在VectorDinamic<Element>::iterator()
的定义中指定模板参数:
template <class Element>
VectorDinamic<Element>::VectorDinamic() {
capacitate = INIT_CAPACITY;
elems = new Element[capacitate];
lg = 0;
}
template <class Element>
vectorDinamicIterator<Element>* VectorDinamic<Element>::iterator()
{
vectorDinamicIterator<Element>* iter =
new vectorDinamicIterator<Element>(this);
return iter;
// or simply
// return new vectorDinamicIterator<Element>(this);
// but I don't see why you return a pointer to a dynamically allocated
// iterator, instead of just an iterator
}
答案 1 :(得分:1)
您没有在变量声明及其构造函数中指定模板。
要修复,只需return new vectorDinamicIterator<Element>(this);