C + + code appreciation, such as Object transfer

Source: Internet
Author: User

#include <iostream>using namespace STD;classa{Private:intX Public: A (): X (0) {x =0;cout<<"Construct"<< Endl; AConstA &a) {x = a.x;cout<<"Construct copy"<< Endl; } ~a () {cout<<"Destruct"<< Endl; }//A operator () (int rhs)a&operator()(intRHS) {x + = RHS;return* This; }intGetX () {returnX }};voidMain () {{A A;cout<< A (1)(2)(3). GetX () << Endl;cout<< a.getx () << Endl; }}

The code presented in this section includes the following:
+ Reference Pass
+ Type Object Pass parameter
+ Overloaded operator Continuous invocation

In the case where the a& operator () (int RHS) function type declaration is defined, there is no new object in between, and each operation is the same object, so the final output is:

In the case of defining a operator () (int RHS) function type declaration, a new anonymous object is generated in the middle, and the copy constructor is automatically called, printing construct copy. The final output is

The trick to repeatedly invoke an overloaded operation is that the return type is a reference of the original type.
This technique can be used to implement recursive access to a path, realizing the idea of a previous blog post: http://blog.csdn.net/lonelyrains/article/details/45093007.

C + + code appreciation, such as Object transfer

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.