Learn about polymorphism in C + +

Source: Internet
Author: User
Tags arithmetic operators

First, the concept

Polymorphism is one of the three main features of object-oriented programming. Encapsulation is the foundation, inheritance is the key, polymorphism is complementary, and polymorphism exists in the environment of inheritance. The meaning of polymorphism is a variety of states. Two kinds of polymorphism are supported in the C + + language. One is function overloading and operator overloading, also known as Static polymorphism, and the other is dynamic and virtual functions, called dynamic polymorphism. The first and second virtual functions are mainly discussed here.

1. Function overloading

function overloading simply means giving multiple meanings to a functional name. The C + + language allows you to define several different implementations of functions within the same scope in the same name. Defining this overloaded function requires that the parameters of the function be different or at least one type, or that the number is different, or that the order is different. The number and type of arguments are the same, and only overloaded functions that return different values are illegal. because the compiler chooses the overloaded function of the same name only to consider the list of function parameters, that is to choose according to the number of arguments in the function parameter list, the parameter type, or the order of the parameters.

Example: constructor overloading of the string Class (compilation environment: VS2013)

#define  _crt_secure_no_warnings 1#include <iostream>using namespace std;# Include <string.h>class string{public:string (char *s) {Length = strlen (s);p s  = new char[length + 1];strcpy (ps, s);} String (string &s) {length = s.length;ps = new char[length + 1]; strcpy (ps, s.ps);} String (int size = 20) {length = size;ps = new char[length + 1 ];*ps =  ' + ';} ~string () {delete ps;} Int getlen () {return length;} Void print () {Cout << ps << endl;} private:char* ps;int length;}; Int main () {string str1 ("String"); Str1.print (); Cout << str1.getlen ()  <<  endl;char *ps1 =  "String pionter"; STRING&NBSP;STR2 (PS1); STRING&NBSP;STR3 (STR2); Str3.print (); Cout << str3.getlen ()  << enDl;system ("pause"); return 0;} 

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/7F/30/wKiom1cV_C-QJ55yAAAqGqinZhI641.png "title=" Untitled 1.png "alt=" Wkiom1cv_c-qj55yaaaqgqinzhi641.png "/>

The constructor for the string class was overloaded three times,

STR1 ("string") calls the constructor String (char *s);

STR2 (PS1) calls the constructor string (char *s);

STR3 (STR2) calls the constructor string (string);


2. Operator overloading

Operator overloading overloading is the ability to assign multiple definitions of an existing operator to multiple functions.

Definition method: Class name operator operator (argument list) {}

The following operators allow overloading in C + +:

    • Arithmetic operators: +,-, *,/,%, + +,--

    • Bitwise manipulation Operators: &,|, ~, ^, <<,>>

    • Logical operators:!, &&, | |

    • Comparison operators: <, <=;, >=, = =,! =

    • Assignment operators: =, + =,-=, *=,/=,%=, &=, |=, ^=, <<=, >>=

    • Other operators: [], (),->, ', New, delete, new[], delete[]

The following operators do not allow overloading:

·,·*, ::,?

Note for using operator overloading:

    1. The precedence and binding of the original operator is not changed when the user is redefining the operator. Without changing the operands and syntax structure of an operator, a single-mesh operator can only be overloaded to a single-mesh operator, and the binocular operator can only overload the binocular operators.

    2. Overloaded operators cannot have two semantics.

Example of operator overloading:

Operator Overloading #include <iostream>using namespace std;class complex{//friend complex  operator+ (COMPLEX&NBSP;C1,&NBSP;COMPLEX&NBSP;C2);p Ublic:complex (double real = 0.0,  double image = 0.0):  _real (Real),  _image (image) {}complex (const complex& &NBSP;C):  _real (C._real),  _image (c._image) {}complex operator+ (CONST&NBSP;COMPLEX&AMP;&NBSP;C1) { Return complex (_real + c1._real, _image + c1._image);} complex operator-(CONST&NBSP;COMPLEX&AMP;&NBSP;C1) {Return complex (_real - c1._real, _ Image - c1._image);} complex operator* (CONST&NBSP;COMPLEX&AMP;&NBSP;C1) {Return complex (_real*c1._real - _image* C1._image, _real*c1._image + _image*c1._real);} complex operator/(CONST&NBSP;COMPLEX&AMP;&NBSP;C1) {Return complex (_real*c1._real + _image *c1._image)  /  (c1._image*c1._image + c1._reAl*c1._real),  (_image*c1._real - _real*c1._image)  /  (c1._image*c1._image +  c1._real*c1._real));} complex& operator+= (CONST&NBSP;COMPLEX&AMP;&NBSP;C1) {_real = _real + c1._real;_ Image = _image + c1._image;return *this;} complex& operator-= (CONST&NBSP;COMPLEX&AMP;&NBSP;C1) {_real = _real - c1._real;_ Image = _image - c1._image;return *this;} Complex& operator*= (CONST&NBSP;COMPLEX&AMP;&NBSP;C1) {double tmp = _real;_real =  _real*c1._real - _image*c1._image;_image = tmp*c1._image + _image*c1._real ; return *this;} Complex& operator/= (CONST&NBSP;COMPLEX&AMP;&NBSP;C1) {double tmp = _real;_real =   (_real*c1._real + _image*c1._image)  /  (c1._image*c1._image + c1._real*c1._ Real);_image =  (_image*c1._real - tmp*c1._imaGE)  /  (c1._image*c1._image + c1._real*c1._real); return *this;}   Only compare Real part bool operator< (const complex& c) {if  (_real<c._real) {return  true;} Else{return false;}} Bool operator> (const complex& c) {if  (_real>c._real) {return true;} Else{return false;}} bool operator<= (Const complex& c) {if  ((_real<c._real)  | |   (_real == c._real)) {return true;} Else{return false;}} Complex& operator= (const complex& c) {if  (this != &c) {_real =  c._real;_image = c._image;} Return *this;} bool operator== (const complex& c) {return _real == c._real &&  _image == c._image;} bool operator&& (const complex& c) {return true;}   Front complex& operator++ () {_real++;_image++;return *this;}   Rear-facing + +complex operator++ (int) {complex temp (*this); _real++;_image++;return temp;} complex& operator--() {_real--;_image--;return *this;} complex operator--(int) {complex temp (*this); _real--;_image--;return temp;} Void display () {cout << _real <<  ","  << _image < <  "I" &NBSP;&LT;&LT;&NBSP;ENDL;COUT&NBSP;&LT;&LT;&NBSP;ENDL;} private:double _real;double _image;}; Int main () {complex c1 (1, 1); COMPLEX&NBSP;C2 (2, 1); complex c3; COMPLEX&NBSP;C4 (1, 1); COMPLEX&NBSP;C5 (1, 1);bool bo = true;c3 = c1 + c2;cout <<   "c3 = c1 + c2  "  << endl;c3.display (); c3 = c1  - c2;cout <<  "c3 = c1 - c2  "  << endl ; C3.display ();c3 = c2*c1;cout <<  "C3&NBSP;=&NBSP;C1&NBSP;*&NBSP;C2&Nbsp;  " << endl;c3.display ();c3 = c2 / c1;cout << " C3  = c1 / c2   " << endl;c3.display ();c1 += c2;cout  <<  " c1 += c2  "  << endl;c1.display ();c1 -= c2; cout <<  " c1 -= c2  "  << endl;c1.display (); c1 *=  c2;cout <<  " c1 *= c2  "  << endl;c1.display (); c1 /= c2;cout <<  " c1 /= c2  "  << endl; C1.display ();bo = c1 < c2;if  (bo) {cout <<  "C1 < c2  is true "&NBSP;&LT;&LT;&NBSP;ENDL;} else{cout <<  "C1 < c2 is false" &NBSP;&LT;&LT;&NBSP;ENDL;} c4++;cout <<  " c4++  "  << endl;c4.display (); ++c5;cout <<  " ++c5  "  << endl;c5.display ();c4--;cout <<   " c4--  "  << endl;c4.display ();--c5;cout <<  " -c5    " << endl;c5.display (); System (" pause "); return 0;}


The arithmetic of complex numbers, ++,--(front and rear) are overloaded.


3. Virtual functions

When you use the virtual keyword to modify a function, it indicates that the function is a virtual function and the derived class needs to be re-implemented, and the compiler dynamic binding will be implemented.

Summarize:

1. the derived class overrides the virtual function of the base class to implement polymorphism, requiring the function name, parameter list, and return value to be exactly the same . (excluding covariance)

2. The virtual function is defined in the base class, and in the derived class, the function always retains the attributes of the virtual function.

3. only member functions of a class can be defined as virtual functions. a static member function cannot be defined as a virtual function.

4 . If you define virtual functions outside of a class, you can only add the virtual keyword when declaring a function, not add it when you define it.

5. The constructor cannot be defined as a virtual function, although operator= can be defined as a virtual function, but it is better not to do so, it is easy to confuse

6 . Do not call virtual functions in constructors and destructors, objects are incomplete in constructors and destructors, and undefined behavior may occur.

7, it is best to declare the destructor of the base class as a virtual function. (destructors are special because the destructor of a derived class is not the same as the destructor name of the base class, but constitutes an overlay, where the compiler does special processing)

8 . Virtual tables are common to all class object instances .







Learn about polymorphism in C + +

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.