[CPP] Reload operator Rule Summary

Source: Internet
Author: User

The overload operator beautifies the syntax of normal functions. I didn't add any basic things to the language, but improved comprehensibility and reduced maintenance costs. operator Overloading should be used when users need it, but it should be used only in the semantic mode that users are familiar.

1. Reload rules

Operators that cannot be overloaded:. And. * And? : And: and sizeof and typeid

There are two basic options for heavy-duty operators: member functions of the class or friend functions. The recommended rules are as follows:

Operator

Recommended

All unary Operators

Member Functions

= () []->

Must be a member function

+ =-=/= * = ^ = & =! ==>>=<=, It seems that all the equal signs are here.

Member Functions

All other binary operators, such as-, + ,*,/

Youyuan Function

2. Parameters and return values

When the parameter is not changed, it is generally passed by const reference (if the member function is used for overload, the function is also const ).

Determine the return value:

1) if the return value may appear on the left side of the = sign, it can only be used as the left value and a non-const reference is returned.

2) If the return value can only appear on the right side of the = sign, the value can only be used as the right value, and the value of the const type or the const type is returned.

3) if the return value may appear on the left or right of the = sign, the return value must be the left value and a non-const reference is returned.

3. Several examples

  3.1 using the binary algorithm, we recommend that you use a friend function overload, which is similar to an internal operation.

   1:  class Integer {
   2:      int _val;
   3:  public:
   4:      Integer(int val = 0) : _val(val) {}
   5:      
6: // binary operators reload as member functions
   7:      const Integer operator+(const Integer& i) const {
   8:              return Integer(_val + i._val);
   9:      }
10: // The binary operator is overloaded as a friend function.
  11:      friend const Integer operator-(const Integer& ,const Integer&);
  12:  };
  13:  const Integer operator-(const Integer& l,const Integer& r) {
  14:      return Integer(l._val-r._val);
  15:  }
  16:   
  17:  Integer a(40), b(12);
  18:   
  19:  a+b;       
20: A + 1; // correct. The left operand is an integer object. + the right operand is resolved to 1 according to the integer member function, and automatic type conversion is performed.
21: 1 + A; // error. The left operand is 1. + is parsed according to the regular operator. The right operator is an integer object. 1 cannot be converted.
22: A-B; // correct
23: A-1; // correct
24: 1-A; // correct. The left operand is 1, and the right operator is an integer object.-As a friend function of integer, 1 is converted to an integer object.

1) in the above Code, the binary operator + is used as a member function overload and cannot be correctly parsed during calls such as 1 +. Binary operators-as a friend function overload, are used in a way similar to conventional-operator operations.

2) If the preceding operator is overloaded, the Operation Result of the operator must be on the right of the = sign. The return value is a right value and the return value is a const value.

3.2 ++ and -- Operator Overloading

1) operator ++ has two forms: suffix form I ++, which contains a virtual parameter of the int type during overload. The prefix is in the form of ++ I. When it is overloaded, there is no virtual parameter. Operator -- the situation is similar.

2) The suffix form (I ++, I --) returns the copy (or return void) of the original state, and the prefix form (++ I, -- I) returns * This through reference. This is to be consistent with the internal type.

The prefix version (++ I, -- I) returns a left value, that is, a non-const reference.

The suffix version (I ++, I --) returns a right value, that is, a const value.

   1:  class Example{
   2:  public:
   3:  Example(int i,int j) { _x = i; _y = j;}
4: // when there is no virtual parameter in the prefix form (++ I) Reload, * This is returned through reference, that is, the value after the change is returned.
   5:  const Example& Example::operator++ () {
   6:            ++_x;
   7:            ++_y;
   8:            return *this;
   9:  }
10: // when the suffix form (I ++) is overloaded, there is a virtual parameter of the int type, and a copy of the original state is returned.
  11:  const Example Example::operator++ (int) {
  12:              Example tmp(*this);
  13:              ++_x;
  14:              ++_y;
  15:              return tmp;    
  16:  }
  17:  int _x, _y;        
  18:  };
  19:   

 

3.3 overload subscript operator []

Because the subscript operator can appear on the left or right of =, the return value must be a left value. Generally, the return value is specified as a reference. To access the const object, there are two versions of the subscript operator overload: Non-const and Const.
   1:  class Array {
   2:  public:
   3:      Array(int size) : _size(size) { _val = new int[_size];}
   4:      int& operator[] (int index) { return _val[index]; }
   5:      const int& operator[] (int index) const { return _val[index]; }
   6:  private:    
   7:      int _size;
   8:      int* _val;
   9:  };
  10:  Array array_a(10);
11: array_a [0] = 1; // [] the overloaded version has a non-const version.

3.4 overload input/output operators

Because the >>and <operator always needs to be assigned a value, a left value must be returned.

   1:  class A
   2:  {
   3:  private:
   4:      int a,b;
   5:  public:
   6:      A(int na = 0, int nb = 0):a(na), b(nb){}
   7:      friend istream& operator>>(istream& is, A& aa);
   8:      friend ostream& operator<<(ostream& os, const A& aa);
   9:   
  10:  };
  11:  ostream& operator<<(ostream& os, const A& aa) {
  12:      os << aa.a << " " << aa.b;
  13:      return os;
  14:  }
  15:   
  16:  istream& operator>>(istream& is, A& aa) {
  17:      is >> aa.a >> aa.b;
  18:      return is;
  19:  }

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.