简体   繁体   中英

Why I got an incomplete type error and how to solve it?

This is a code a got for now but it doesnt compile due to an incomplete variable type container::iterator error. The class and the iterator are still pretty simple since I am trying to figure out how to organise my code.

template <typename T> class container {
    using size_type = std::size_t;
    using pointer           = T*;
    using const_pointer     = const T*;
public:
    class iterator;
    container (size_type n=0):  data {n>0 ? new T[n]:nullptr}, size {n>0 ? n:0}{};
    container (iterator begin, iterator end){};
    ~container (){ delete[] data; };
private:
    pointer     data;
    size_type   size;
};

template <typename T> class container<T>::iterator {
public:
    iterator (pointer p): current {p} {};
    iterator& operator++ (){ current++; return *this; };
    iterator& operator-- (){ current--; return *this; };
    reference operator* (){ return *current; };
    bool operator== (const iterator& b) const { return current == b.current; };
    bool operator!= (const iterator& b) const { return current != b.current; };
private:
    pointer current;
};

I would like to keep the iterator definition out of the container class if possible. Thanks for any replies.

I would like to keep the iterator definition out of the container class if possible.

It isn't, because the arguments for container 's member functions cannot be properly analysed without a definition for their type.

Move it inline.

container (iterator begin, iterator end){};

That uses iterator but at that point in the code there's no definition of iterator , only a declaration. You'll need to define the structure of your iterator before you can even declare this constructor.

You could alter this constructor to take references. Then you can declare it within your class but then define it below the definition for iterator. IMO this isn't the best way to go, but it's possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM