PKU C + + programming Practice Learning Note 4 operator overloading

Source: Internet
Author: User
Tags shallow copy

Fourth operator overloading

4.1 Basic concepts of operator overloading 1. Operator 2. Custom data types and operator overloading

C + + provides the means for data abstraction: User-defined data types-class
? Call the member function of the class, manipulate its object

Class is not convenient for manipulating objects, such as member functions
? In mathematics, two complex numbers can be directly performed with +/-arithmetic Vs. In C + +, direct + or-for complex numbers is not allowed

3. Operator overloading
  • You can also use the operators provided by C + + directly for abstract data types
    ? More Concise procedures
    ? Code easier to understand
  • Operator overloading
    ? Assigning multiple meanings to an existing operator
    ? Different types of behavior when you make the same operator work on different types of data
  • Objective
    ? Extends the scope of the operators provided in C + + for use in the abstract data types represented by the class
  • The same operator, which behaves differently for different types of operands
    ? (5,10i) + (4,8i) = (9,18i)
    ? 5 + 4 = 9
  • The essence of operator overloading is function overloading
    return value type operator operator (formal parameter list)
    {
    ......
    }
  • At program compile time:
    ? Call to operator function with an expression that contains an operator
    ? arguments to operator functions, operand of operator
    ? Operator is overloaded multiple times, which operator function is called based on the type of the argument
    ? Operators can be overloaded into normal functions
    ? member functions that can also be overloaded into classes
4. Operator overloading isCommon Functions
Class Complex {public  :    Complex (Double r = 0.0, double i= 0.0) {      real = R;      imaginary = i;    }  Double Real; Real part  double imaginary;//Imaginary part}; Complex operator+ (const Complex & A, const Complex & B) {  return Complex (A.real+b.real, A.imaginary+b.imagina ry);} "Class name (parameter table)" represents an object complex a (), B (2,3), c;c = a + b;//equivalent to what?  Operator+ (A, B)
When overloading is a normal function,Number of parameters is operator mesh
5. Operator overloading ismember functions
Class Complex {public  :    Complex (double r= 0.0, double m = 0.0): Real (R), imaginary (m) {}//constructor    Comp Lex operator+ (const Complex &); Addition    Complex operator-(const Complex &);//Subtraction  private:    double real;//Real part    D Ouble imaginary; Imaginary part};//Overloaded addition Operatorcomplex complex::operator+ (const Complex & operand2) {  return C Omplex (real + operand2.real,imaginary + operand2.imaginary);} Overloaded Subtraction Operatorcomplex complex::operator-(const Complex & operand2) {  return Complex (real-op erand2.real,imaginary-operand2.imaginary);} int main () {Complex x, y (4.3, 8.2), Z (3.3, 1.1); x = y + z;//equals what?  Y.operator+ (z) x = y-z;//equals what?  y.operator-(z) return 0;}
When overloaded as a member function,the number of parameters is the number of operators reduced by one
4.2 Overload of the assignment operator 1. The assignment operator ' = ' overloads the type on either side of the assignment operator can be mismatched
? Assigns an int type variable to a complex object
? Assigns a char * type string to a String object

Overloaded assignment operator ' = ' Required

assignment operator ' = ' can only be overloaded as a member function

Write a variable-length string class
? A member variable that contains a char * type
-point to dynamically allocated storage space
? This storage space is used to hold the string ending with '/'

Class String {  private:    char * STR;  Public:    String (): str (NULL) {}//constructor, initialize STR as NULL    const char * C_STR () {return str;}//return value is const type, ensure STR will not be repaired Change. such as char* P=str.c_str (), the compiler will error, type mismatch.    char * operator = (const char * s);    ~string ();//need to consider whether a String object points to a dynamically allocated storage space}; Overloading ' = ' makes obj = "Hello" capable of forming char * string::operator = (const char * s) {  if (str) delete [] str;  if (s) {//s is not null to execute copy    str = new Char[strlen (s) +1];    strcpy (str, s);  }  else    str = NULL;  return str;} String::~string () {  if (str) delete [] str;}; int main () {  String s;  s = "good Luck,";  cout << s.c_str () << Endl;  String s2 = "hello!"; If this statement is not commented out will be error  s = "Shenzhou 8!";  cout << s.c_str () << Endl;  return 0;}
2. Meaning of overloaded assignment operators-shallow copy and deep copy

S1 = S2;

    • Shallow copy/Shallow copy
      Perform byte-by-bit replication work




S1 and S2 point to the same piece of dynamically allocated memory area, so when S1 and S2 die at the same time, this memory space will be released two times successively. This can lead to a serious memory error and may even cause the program to abort unexpectedly.
So we see that such a shallow copy, or a shallow copy of the work itself, does not achieve what we want to achieve in the middle of the STR string like S2 copied to the space that the S1 itself points to.

    • Deep copying/Deep copy
      Copies the contents of a pointer variable in one object to the point where the pointer member object is pointing to another object



Add member functions in class MyString:

String & operator = (const String & s) {  if (str) delete [] str;  str = new Char[strlen (S.STR) +1];  strcpy (str, s.str);  return * this;}

3. Thinking

Is there a problem considering the following statement?
MyString s;    s = "Hello"; s = s;

Correct wording:

String & string::operator = (const String & s) {  if (str = = S.STR) return * this;//increase this line  if (str) Delete [] St R;  if (S.STR) {//S.STR is not null to execute copy    str = new Char[strlen (S.STR) +1];    strcpy (STR,S.STR);  }  else    str = NULL;  return * this;}

4. Discussion of operator = return value type
    • is void good or bad?
      Consider: a = b = C;
      Equivalent to A.operator= (b.operator= (c));
    • String is good? Why string &
      Operator overloading, good style--try to preserve the original attributes of the operators
      Consider: (a=b) =c; Will modify the value of a
      respectively equivalent to: (a.operator= (b)). Operator= (c);

5. Is there no problem with the string class above?

When you write a copy constructor for the string class, you face the same problem as ' = ', which is handled in the same way

String::string (String & s) {  if (s.str) {    str = new Char[strlen (S.STR) +1];    strcpy (str, S.STR);  }  else    str = NULL;}

The 4.3 operator overload is friend function 1. Operator overloading is friend
    • Typically, overloading an operator as a member function of a class
    • Overloading is a friend function case:
      ? member functions do not meet usage requirements
      ? Normal functions, and cannot access private members of a class
Class complex{    double Real, imag;  Public:    Complex (Double R, double i): Real (R), Imag (i) {};    Complex operator+ (Double r);}; Complex complex::operator+ (Double R) {//can interpret c+5  return Complex (real + R, imag);}
After the above overloads:
Complex C;
c = C + 5; There is a definition, equivalent to C = C.operator + (5);
But:
c = 5 + C; Compilation error
To make the above expression possible, the + overload is required as a normal function
Complex operator+ (Double R, const Complex & c) {  //can interpret 5+c  return Complex (C.real + R, C.imag);}
Normal function cannot access private member---operator + overloaded tofriend function
Class Complex {    double real, imag;  Public:    Complex (Double R, double i): Real (R), Imag (i) {};    Complex operator+ (Double R);    Friend Complex operator + (double R, const Complex & c);};

PKU C + + programming Practice Learning Note 4 operator overloading

Related Article

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.