Just touchedC ++New students are often confused by front ++ and back ++. This concept is very important in C ++. It is necessary to understand the front ++ and back ++. The following describes the differences between front ++ and back ++.
Front ++:
- type operator++);
Rear ++:
- const type operator++int );
In order for the compiler to distinguish between front and back ++, C ++ requires that the suffix form has an int type parameter. When a function is called, the compiler passes a 0 value as the int parameter to the function. Otherwise, it cannot be distinguished because only the object itself is an input parameter.
The following is a simple example:
- Class CInt {
- Private:
- Int m_value;
- //
- };
- CInt & CInt: operator ++ () // There is no parameter in front of it and a reference is returned.
- {
- This-> m_value + = 1;
- Return * this;
- }
- Const CInt: peartor ++ (Int) // There is an anonymous parameter at the end and the const value is returned.
- {
- CInt old = * this;
- ++ (* This );
- Return old;
- }
The preceding implementation explains a key problem: the prefix is more efficient than the Postfix. the Postfix needs to construct a temporary object and return it.
So why are the front and back return parameters different?
The frontend only performs operations on itself and returns itself, so that you can directly operate on the returned object, as shown in figure
- ++it)->function)
When the returned result is not the original object, you can perform additional operations to change the status of the temporary object.
So why not return const? Because you cannot do this, the returned reference will be invalid and the temporary object will no longer exist.
Therefore, if a const object is returned in the backend, the temporary object is limited to incorrect operations, and the caller is explicitly notified that the object is only a copy of the original object.
Another reason is that the built-in int type does not support I ++. If the post ++ returns a modifiable copy, it will be different from the built-in int type. Therefore, modification to the return value should be prohibited.
We hope that the above content will help you.