在C ++中将类声明转发到另一个类中并带来好处

时间:2017-08-19 04:18:11

标签: c++ class forward-declaration

我们在Iterator声明了Mylist前锋。 Mylist的成员函数可以使用它(例如return类型):

template<class Elem>
class Mylist {

public:
    class Iterator;

    ...

    Iterator begin() const;  // iterator to the first element
    Iterator end() const;  // iterator to one beyond the last element

    Iterator insert(Iterator p, const Elem& v);  // insert v into the list after p

private:
...
    class Link;

protected:
    Link* first;
    Link* last;
};

//*****************************************

template<class Elem>
class Mylist<Elem>::Link {

public:
    Link(Elem v, Link* p = nullptr, Link* s = nullptr) : 
        val(v), prev(p), succ(s) { }

    Link* prev = nullptr;
    Link* succ = nullptr;
    Elem val;
};

//****************************************

template<class Elem>
class Mylist<Elem>::Iterator {

private:
  Link* curr;    

public:
    Iterator(Link* p) : curr(p) {  }

    Iterator& operator++() { curr = curr->succ; return *this; } // forward
    Iterator& operator--() { curr = curr->prev; return *this; } // backward

    Elem& operator*() { return curr->val; } // get value (dereference)

    bool operator==(const Iterator& b) const { return curr == b.curr; }
    bool operator!=(const Iterator& b) const { return curr != b.curr; }
};

但是类Iterator p )的对象是否也可以使用任何成员函数或类Mylist的东西,它已被前向声明?<登记/> 如果是这样,怎么样?

0 个答案:

没有答案