How do I refer to the "owner class" in C ++?
I have some code that looks like this:
template<class T>
class list
{
public:
class iterator;
};
template<class T>
class list::iterator
{
public:
iterator();
protected:
list* lstptr;
};
list<T>::iterator::iterator()
{
//???
}
I want to make a constructor list::iterator
to make it a iterator::lstptr
pointer to the list from which it was called. I.e:.
list xlst;
xlst::iterator xitr;
//xitr.lstptr = xlst
How can I do it?
And also I am referring to my constructor-iterator-constructor, or I need to do something like this:
template<class T>
class list<T>::iterator
{
public:
list<T>::iterator();
protected:
list* lstptr;
};
You can pass a list to the iterator constructor:
list xlst;
list::iterator xitr(xlst);
Or you can make an iterator factory function:
list xlst;
list::iterator xitr = xlst.create_iter();
In a functional case, a factory function create_iter()
can be used this
to denote an attached list.
a source to share
Since you don't need to change (reset) the pointer and there is no need for a NULL value, I would use a reference instead. Alternatively, you can use an initializer list when assigning to a member variable (and should if you are using a reference).
template<class T>
class list::iterator
{
public:
iterator( list& parent ) : lstptr( parent ){}
protected:
list& lstptr;
};
And as mentioned earlier: use the factory method inside the list class to construct objects of type list :: iterator.
a source to share