Reputation: 65
Help me, please, realize overload operator++ in doubly linked list. I have a two classes A and B.
class A {
private:
int h;
int a;
public:
A *next, *prev;
friend A operator ++(A &, int);
};
A operator ++(A &t, int) {
A temp = t;
temp.h++;
temp.a++;
return temp;
}
class B {
private:
A *head, *tail;
public:
void incValue();
};
void B::incValue() {
while(head != nullptr) {
head++;
head = head -> next;
}
}
After execution method incValue() head = NULL I don't understand why this don't work.
P.S. This code must be eq. head++
head -> setH(head -> getH() + 1);
head -> setA(head -> getA() + 1);
Upvotes: 1
Views: 1046
Reputation: 129
First. You overloading operator to use first parameter as a class -> you don't need to make operator friend.
class A {
private:
int h;
int a;
public:
A *next;
A *prev;
void operator ++ ( int );
};
This overloaded operator will work with object of class A. So to use it just write:
A a;
a++;
And realization of this operator will be:
void A::operator ++ ( int )
{
h++;
a++;
}
You realization will work only like:
A a;
a = a++;
Because operator ++ return new copy of A object, but incremented h and a members.
Second. About walking in list:
Your while will stop when head == NULL, so after execution while loop head pointer will be equal to 0. So, that loop statement head++
will be executed for every object.
Upvotes: 0
Reputation: 13451
If you want to call the overloaded operator++
for A
you need to call (*head)++
in your B::incValue
method.
Upvotes: 1
Reputation: 310930
To overload operator ++ you need to support some data member of the linked list that will define the current position in the list. Also you need a member function that will reset the current position in the linked list.
Upvotes: 1