Temporary object reference binding

Source: Internet
Author: User

A temporary object can only be bound with a constant reference. In this case, only constant functions can be called for constant reference.

However, you can directly call member functions on a temporary object (if there are non-constant functions and constant functions, the call of non-constant functions is preferred ).

  1. # Include <stdio. h>
  2. # Include <iostream>
  3. Using namespace STD;
  4. Class {
  5. Public:
  6. Virtual void func (INT data) {printf ("A1: % d/N", data );}
  7. Virtual void func (INT data) const {printf ("A2: % d/N", data );}
  8. };
  9. Void func (const A & T)
  10. {
  11. T. func (10 );
  12. Cout <"func is called! "<Endl;
  13. }
  14. A test ()
  15. {
  16. Return ();
  17. }
  18. Int main ()
  19. {
  20. // A & A = a (); // error, a () returns a temporary object and can only be bound with a constant reference.
  21. Const A & A = a (); // seccessful
  22. A. func (20); // call a constant function
  23. Func (());
  24. A (). func (1); // call a very large number of functions (if any)
  25. Test (). func (100); // call a very large number of functions (if any)
  26. Return 0;
  27. }

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.