[Zz] C ++ operator overload summary & Return Value Optimization

Source: Internet
Author: User

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;
   

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.