【问题标题】:Why I got an incomplete type error and how to solve it?为什么我收到不完整的类型错误以及如何解决?
【发布时间】:2016-06-13 16:20:05
【问题描述】:

这是一个暂时得到的代码,但由于不完整的变量类型 container::iterator 错误而无法编译。类和迭代器仍然非常简单,因为我试图弄清楚如何组织我的代码。

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

如果可能,我希望将迭代器定义保留在容器类之外。感谢您的任何回复。

【问题讨论】:

    标签: c++ incomplete-type


    【解决方案1】:
    container (iterator begin, iterator end){};
    

    这使用了iterator,但此时代码中没有iterator 的定义,只有一个声明。您需要先定义迭代器的结构,然后才能声明此构造函数。

    可以更改此构造函数以获取引用。然后你可以在你的类中声明它,然后在迭代器的定义下面定义它。 IMO 这不是最好的方法,但有可能。

    【讨论】:

    • 谢谢,我知道这是导致问题的线路。我想知道是否有“常规”解决方法。似乎除了内联定义。
    【解决方案2】:

    如果可能,我希望将迭代器定义保留在容器类之外。

    不是,因为container 的成员函数的参数在没有类型定义的情况下无法正确分析。

    内联移动它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-15
      • 2017-09-14
      • 1970-01-01
      • 1970-01-01
      • 2016-06-08
      • 1970-01-01
      相关资源
      最近更新 更多