Why can't I add pointers?
I have code very similiar to this:
LINT_rep::Iterator::difference_type LINT_rep::Iterator::operator+(const Iterator& right)const
{
return (this + &right);//IN THIS PLACE I'M GETTING AN ERROR
}
LINT_rep::Iterator::difference_type LINT_rep::Iterator::operator-(const Iterator& right)const
{//substracts one iterator from another
return (this - &right);//HERE EVERYTHING IS FINE
}
err msg: Error 1 error C2110: '+' : cannot add two pointers
Why I'm getting an error only in one place and not in both?
742 Evergreen Terrace + 1 = 743 Evergreen Terrace
742 Evergreen Terrace - 1 = 741 Evergreen Terrace
743 Evergreen Terrace - 741 Evergreen Terrace = 2
743 Evergreen Terrace + 741 Evergreen Terrace = ???
Pointer addition is forbidden in C++, you can only subtract two pointers.
The reason for this is that subtracting two pointers gives a logically explainable result - the offset in memory between two pointers. Similarly, you can subtract or add an integral number to/from a pointer, which means "move the pointer up or down". Adding a pointer to a pointer is something which is hard to explain. What would the resulting pointner represent?
If by any chance you explicitly need a pointer to a place in memory whose address is the sum of some other two addresses, you can cast the two pointers to int
, add int
s, and cast back to a pointer. Remember though, that this solution needs huge care about the pointer arithmetic and is something you really should never do.