Q: How do I distinguish the prefix and Postfix formats when operators are overloaded?
(Note: It turns out that this is the term "more effective C ++" when I read a book at night. "M6 really doesn't work if I don't read a book ...)
Answer: In the following example, const fraction operator ++ (INT)
Int Is nothing more than dummy.
It is only used to determine whether ++ is prefix or Postfix.
Remember, if there is a dummy, it is Postfix. Otherwise, it is prefix.
Just like other unary algorithms and logical operations
In fact, this kind of dummy element is only used in the Postfix ++ and --
Example:
Int I = 10;
Cout <I ++ <Endl; // I = 11; suffix addition; first return and then auto-increment; 10
Cout <++ I <Endl; // I = 12; prefix addition; Auto-increment first and then return; 12
Example:
# Include <iostream>
Using namespace STD;
Class Fraction // Number class;
{
Friend ostream & operator <(ostream & out, const fraction & X );
PRIVATE:
Int den; // Increment the step distance so that the self-increment distance is not 1;
Int num; // Number (initial value );
Public:
Fraction (INT d = 1, int n = 0): Den (D), num (n ){}
Fraction & operator ++ () // Prefix auto-increment and overload (prefix)
{
Num + = den; // Auto-increment first, and then return;
Return * this;
}
Const fraction operator ++ (INT) // Suffix auto-increment and overload; (postfix)
{
Fraction old (* This ); // Copy structure (the object parameter is an object ). Returns first and then auto-increment;
++ (* This ); // Call the overloaded pre-version;