Answer the question
In order to leave comments, you need to log in
C++ Operator and its overload?
DATE & operator ++()
{
DATE Copy(*this);
day++;
month++;
year = year + 10;
return *this;
}
DATE& operator ++()
DATE Copy(*this);
Answer the question
In order to leave comments, you need to log in
Well, that's how it's done in C++. The prefix increment operator (++i) has this signature - it returns a reference to the modified object. If you want your class Date
to be able to do ++date
, then you need to redefine such an operator. This allows you to write more readable and shorter code. Instead date.IncremeantAndReturn()
, you can use the idiomatic ++date
, or even something like while (++date < deadline)
. It is not necessary to do this, but sometimes it is very convenient and useful.
The operator must return the modified value, which is why *this is returned after it has been incremented;
Not used in this code Сopy
. It's not needed here at all. the copy will be needed for the postfix increment (i++), which must return an unchanged object.
Broadcast*this
to the Copy constructor is to call the copy constructor to suddenly create a copy of the current object. Think about how you can copy the current object? It is necessary to assign the current object to the new object, or pass the current object to the constructor. But how to pass the current object? You have a pointer to it this. By dereferencing this pointer (*this) you can just pass the current object to the right place.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question