0

我想做一个模板向量,但是当我返回迭代器时出现问题。我一直在搜索所有互联网,但没有找到任何解决方案。这是代码:

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

我省略了一些方法实现以保持代码简短,我在出现错误的地方添加了注释,但我不知道为什么。没有“迭代器”方法,代码工作得很好。

4

2 回答 2

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
}
于 2013-05-27T20:13:40.203 回答
1

您缺少在变量声明及其构造函数中指定模板。

要修复,只需return new vectorDinamicIterator<Element>(this);

编辑:哦,是的,正如 DyP 所注意到的,您缺少前向声明。由于某些原因,我没有把目光放在那部分。

于 2013-05-27T20:07:08.187 回答