Pku c ++ Programming Practice Study Notes 4 Operator Overloading

Source: Internet
Author: User

Pku c ++ Programming Practice Study Notes 4 Operator Overloading

Chapter 4 Operator Overloading

4.1 basic concepts of Operator Overloading 1. Operators
2. Custom Data Types and Operator Overloading

C ++ provides data abstraction means: You can define your own data types-classes.
? Call a member function of a class-> operate on its objects

Class member functions-> inconvenient to operate on objects
? In mathematics, two plural numbers can be directly used for the +/-equal operation Vs. In C ++, it is not allowed to directly use + or-for the plural.

3. The operator overload can also directly use the operators provided by C ++ for abstract data types.
? Simpler Program
? Code is easier to understand Operator Overloading
? Give multiple meanings to existing operators
? When the same operator acts on different types of data-> different types of behavior
? Extends the applicability of the operators provided in C ++ to be used for the same operator of abstract data types represented by classes. Operations of different types of operands are different.
? (5, 10i) + (4, 8i) = (9, 18i)
? 5 + 4 = 9 the essence of Operator Overloading is function overloading.
Operator of Return Value Type (parameter table)
{
......
}
During program Compilation:
? Call the expression containing the operator-> to the operator Function
? Returns the operand of an operator> the parameter of an operator.
? When an operator is reloaded multiple times, it determines which operator to call based on the type of the real parameter.
? Operators can be overloaded into common functions.
? It can also be overloaded as a member function of the class.
4. The operator overload is a normal function.
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 (. real + B. real,. imaginary + B. imaginary);} // "Class Name (parameter table)" indicates a Complex a (1, 2), B (2, 3), c; c = a + B; // What is the equivalent? Operator + (a, B)
When the overload is a common function, the number of parameters is the number of operators
5. Reload operators as member functions
Class Complex {public: Complex (double r = 0.0, double m = 0.0): real (r), imaginary (m) {}// constructor Complex operator + (const Complex &); // addition Complex operator-(const Complex &); // subtraction private: double real; // real part double imaginary; // imaginary part}; // Overloaded addition operatorComplex: operator + (const Complex & operand2) {return Complex (real + operand2. Real, imaginary + operand2.imaginary);} // Overloaded subtraction operatorComplex: operator-(const Complex & operand2) {return Complex (real-operand2.real, imaginary-operand2.imaginary );} int main () {Complex x, y (4.3, 8.2), z (3.3, 1.1); x = y + z; // What is the equivalent? Y. operator + (z) x = y-z; // What is the equivalent? Y. operator-(z) return 0 ;}
When the overload is a member function, the number of parameters is the number of operators minus one
4.2 reload of the value assignment operator 1. The value assignment operator '=' can be of different types on both sides of the reload assignment operator
? Assign an int type variable to a Complex object
? Assign a char * string to a string object.

The value assignment operator '=' needs to be overloaded'

The value assignment operator "=" can only be used as a member function.

Write a variable-length String
? Contains a char * type member variable
-> Point to the dynamically allocated Bucket
? This bucket is used to store strings ending with '\ 0'

Class String {private: char * str; public: String (): str (NULL) {}// constructor, initialize str as NULL const char * c_str () {return str;} // the return value is of the const type, so that str is not modified. For example, char * p = str. c_str (); the compiler reports an error and the type does not match. Char * operator = (const char * s );~ String (); // check whether the String object directs to the dynamically allocated bucket}; // reload '=' to enable obj = "hello" to set char * String :: operator = (const char * s) {if (str) delete [] str; if (s) {// s is not NULL before 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, the error s = "Shenzhou 8! "; Cout <s. c_str () <endl; return 0 ;}
2. Meaning of the overload assignment operator-Shortest copy and deep copy

S1 = S2;

 

Shortest copy/shortest copy
Perform byte-Specific Replication

 




S1 and S2 point to the same dynamically allocated memory area. When S1 and S2 die out at the same time, the memory space will be released twice. This will lead to serious memory errors, and may even lead to unexpected program suspension.
So we can see that such a shortest copy, or the shortest copy cannot implement the str string in the middle of S2 that we want to implement and copy it to the space that S1 points.

 

Deep copy/deep copy
Copy the content pointed to by the pointer variable in an object to the position pointed to by the pointer member object in another object.

 

Add a member function to 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

 

Are there any problems with the following statements?
MyString s; s = "Hello"; s = s;

Correct syntax:

String & String: operator = (const String & s) {if (str = s. str) return * this; // Add this line if (str) delete [] str; if (s. str) {// s. str = new char [strlen (s. str) + 1]; strcpy (str, s. str);} else str = NULL; return * this ;}

 

4. Can I discuss the operator = return value type void?
Consideration: a = B = c;
// Equivalent to a. operator = (B. operator = (c); String? Why is it String &
A good style when operators are overloaded -- retain the original features of operators as much as possible
Consider: (a = B) = c; // The value of a is modified.
They are equivalent to: (a. operator = (B). operator = (c );
5. Is the above String class okay?

 

When writing a copy constructor for the String class, it will face the same problem as '=' and be processed 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;}

4.3 Operator Overloading is a membership function. 1. Operator Overloading is usually a membership function with the operator being overloaded as a membership function:
? Member functions cannot meet usage requirements
? A common function cannot be a private member of the callback class.
Class Complex {double real, imag; public: Complex (double r, double I): real (r), imag (I ){}; complex operator + (double r) ;}; Complex: operator + (double r) {// c + 5 return Complex (real + r, imag );}
After the above overload:
Complex c;
C = c + 5; // defined, equivalent to c = c. operator + (5 );
However:
C = 5 + c; // compilation Error
To make the above expression valid, You need to reload + as a common function.
Complex operator + (double r, const Complex & c) {// can explain 5 + c return Complex (c. real + r, c. imag );}
Ordinary functions cannot access private members-> reload operators + as user functions
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);};

4.4 instance-variable-length integer array class (variable-length integer array)
Class CArray {int size; // Number of array elements int * ptr; // point to the dynamically allocated array public: CArray (int s = 0 ); // s represents the number of array elements CArray (CArray & );~ CArray (); void push_back (int v); // Add an element v CArray & operator = (const CArray & a) at the end of the array ); // assign an int length () {return size ;}// returns the number of array elements. int & CArray: operator [] (inti) // The returned value is int! A [I] = 4 {// not supported to access array elements based on subscript, // For example, n = a [I] And a [I] = 4; return ptr [I] ;}}; CArray: CArray (int s): size (s) {if (s = 0) ptr = NULL; else ptr = new int [s];} CArray: CArray (CArray & a) {if (! A. ptr) {ptr = NULL; size = 0; return;} ptr = new int [. size]; memcpy (ptr,. ptr, sizeof (int) *. size); size =. size ;}


If we do not write a value assignment constructor, The automatically generated value assignment constructor will execute the value assignment function. The assignment here only assigns the member variables of a1 to a2. The member variable ptr of A1.
If it is assigned to a2, then a2.ptr is equal to a1.ptr. That is to say, both the ptr of a2 and the ptr of a1 point to the same storage space.
CArray ::~ CArray () {if (ptr) delete [] ptr;} CArray & CArray: operator = (const CArray &) {// The Value assignment number is used to make the array stored in the left object of "=". The size and content are the same as those of the right object if (ptr =. ptr) // prevent the return * this; if (. ptr = NULL) {// if the array in a is NULL if (ptr) delete [] ptr; ptr = NULL; size = 0; return * this ;} if (size <. size) {// if the original space is large enough, you do not need to allocate a new space. if (ptr) delete [] ptr; ptr = new int [. size];} memcpy (ptr,. ptr, sizeof (int) *. size); size =. size; return * this;} // CArray & CArray: operator = (const CArray & a) void CArray: push_back (int v) {// Add an element if (ptr) {int * tmpPtr = new int [size + 1] at the end of the array; // re-allocate the space memcpy (tmpPtr, ptr, sizeof (int) * size); // copy the original array content to delete [] ptr; ptr = tmpPtr;} else // The array is originally empty ptr = new int [1]; ptr [size ++] = v; // Add a new array element}

4.5 stream insertion operator and stream extraction operator overload 1. Problem

Cout <5 <"this"; why is it true?

What is cout? "<" Why can it be used on cout?

2. Stream insertion Operator Overloading

Cout is defined in iostream, an object of the ostream class.

"<" Can be used on cout because "<" is overloaded in iostream.

Consider how to reload cout <5; and cout <"this" to make it true?

It is possible to reload a member function of the ostream class as follows:

Void ostream: operator <(int n ){...... // Output n code return ;}

 

Because ostream has been encapsulated, it is impossible to write this overload as a member function, so it is written as a global function.

Cout <5; that is, cout. operator <(5 );
Cout <"this"; that is, cout. operator <("this ");

How can I enable cout <5 <"this"; when it is reloaded?

Ostream & ostream: operator <(int n ){...... // Return * this;} ostream & ostream: operator <(const char * s ){...... // Output s Code return * this ;}
Cout <5 <"this"; what is the form of essentially function call?
Cout. operator <(5). operator <("this ");

 

Suppose the program output below is 5 hello. What should I write?

class CStudent{  public: int nAge;};int main(){  CStudent s ;  s.nAge = 5;  cout << s <<"hello";  return 0;}
ostream & operator<<( ostream & o,const CStudent & s){  o << s.nAge ;  return o;}

 

3. Example

 

(P218) example. It can be omitted.

 




 

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.