Overloading of dereferencer and node iterator
Feb 23, 2018 at 9:35pm UTC
I am creating a queue, and i have some overloading i need to get working.
I start with my two classes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
typedef Person Item;
class Node;
class QIterator
{
private :
Node *node;
public :
QIterator(); // Förvald konstruktor
QIterator(Node *n); // Initieringskonstruktor
Item &operator *() const ;
QIterator &operator ++(); // prefix ++i
QIterator operator ++(int ); // postfix i++
bool operator !=(const QIterator &qi) const ;
};
//---------------------------------------------------------------------------
class QList
{
private :
Node *first, *last;
public :
QList() :first(nullptr ), last(nullptr ) {};
~QList() {};
void enque(Item item);
bool deque(Item &item);
bool del(Item item);
bool isEmpty()const ;
QIterator begin()const { return QIterator(first); }
QIterator end() const { return QIterator(nullptr ); }
};
class Node
{
public :
Node *next;
Item data;
Node(Node *n, Item newData) : next(n), data(newData) {}
};
One of my problems is to overload the dereferencer.
The prototype is:
Item &operator*() const;
The definition:
1 2 3 4 5 6
Item &QIterator::operator *() const
{
Item item = node->data;
return item;
}
This one should return a reference to the Node member data, on which the current node pointer points at.
I cant get it to work
Last edited on Feb 23, 2018 at 10:23pm UTC
Feb 23, 2018 at 10:07pm UTC
Hi,
The
item
variable goes out of scope at the end of the function. It is technically an xvalue (eXpiring value). One can extend it's lifetime by return a const reference:
1 2 3 4 5 6
const Item &QIterator::operator *() const
{
Item item = node->data;
return item;
}
By the way please use code tags: select your code and press the <> button on the formatting menu on the right of screen.
Good Luck !!
Feb 23, 2018 at 10:12pm UTC
return node->data;
Feb 23, 2018 at 10:28pm UTC
I got it working woth the <> button, thank you.
What it the difference between
1 2 3 4 5 6
const Item &QIterator::operator *() const
{
Item item = node->data;
return item;
}
and
1 2 3 4 5 6
QIterator &QIterator::operator ++() {
node = node->next;
return *this ;
}
And how about my other ++ operator QIterator QIterator::operator++(int)
Since it should not return a reference but only whats inside of the node that the iterator points at, would it be enough to "return this" ?
Topic archived. No new replies allowed.