Differences between C ++ Operator Overloading and different methods

Source: Internet
Author: User

The C ++ programming language can be seen as an upgraded version of the C language. It can support all functions in the C language and greatly improve in other aspects. Among them, in the C ++ operator overload ++, -- it must be noted that ++ (--) is before the operand or after the operand, the difference is as follows:

The C ++ operator's heavy load code has been tested correctly (at least I have no problem here ^_^)

 
 
  1. # Include <iostream>
  2. # Include <cstdlib>
  3. Using namespace std;
  4. Template <typename T> class
  5. {
  6. Public:
  7. A (): m _ (0 ){
  8. }
  9. // +
  10. Const T operator + (const T & rhs)
  11. {
  12. // Need to be retried red, but see it is only a demo
  13. Return (this-> m _ + rhs );
  14. }
  15. //-
  16. Const T operator-(const T & rhs ){
  17. // Need to be retried red, but see it is only a demo
  18. Return (this-> m _-rhs );
  19. }
  20. T getM (){
  21. Return m _;
  22. }
  23. // ++ Indicates the previous mode. Here, A reference is returned, allowing ++
  24. A & operator ++ (){
  25. (This-> m _) ++;
  26. Return * this;
  27. }
  28. // ++ Returns A new A type variable and cannot be changed.
  29. // The purpose is to prevent A ++ attacks
  30. Const A operator ++ (int ){
  31. A <T> B = * this;
  32. (This-> m _) ++;
  33. Return B;
  34. }
  35. Private:
  36. T m _;
  37. };
  38. Int main (void ){
  39. Int I = 0;
  40. Cout <++ + I <endl;
  41. // I ++ is not allowed
  42. A <int>;
  43. A <int> B = ++;
  44. Cout <B. getM () <endl;
  45. A <int> c = a ++;
  46. Cout <c. getM () <endl;
  47. Cout <a. getM () <endl;
  48. Int t = a + 2;
  49. Cout <t <endl;
  50. System ("pause ");
  51. Return 0;
  52. }

The preceding section describes how to overload the C ++ operator.

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.