Operator Overloading for C ++ learning notes

Source: Internet
Author: User

Click the original link to open the link.

What is Operator overload?

Operator overloading can be divided into two parts: "operator" and "overload ". When it comes to overloading, it should be no stranger. This is a kind of polymorphism during compilation. In fact, overloading can be divided into function overloading and operator overloading. The difference between operator overloading and function Overloading is that operator overloading must be an operator. Let's take a look at the so-called Operator Overloading:

#include <iostream>  using namespace std;  int main() {     int a = 2 , b = 3;     float c = 2.1f , d = 1.2f;     cout<<"a + b = "<<a+b<<endl;     cout<<"c + d = "<<c+d<<endl;     return 0; }

We can see that the operator "+" is complete.FloatAndIntTwo types of addition calculation, which is the heavy load of operators. These built-in types of Operator Overloading have been implemented, but what if we want to implement a similar addition operation for the classes we have already written ?? For example, now there is such a point class. To add two vertices, the result is that the horizontal and vertical coordinates must be added. At this time, we need to write an operator to reload the function.

View code # include <iostream> using namespace STD; Class Point {Double X; Double Y; public: Double get_x () {return X;} double get_y () {return y ;} point (Double X = 0.0, Double Y = 0.0): x (x), y (y) {}; point operator + (point P );}; // overload operator "+" point: Operator + (point P) {Double X = This-> X + P. x; Double Y = This-> Y + P. y; point tmp_p (x, y); Return tmp_p;} int main () {Point P1 (1.2, 3.1); point P2 (1.1, 3.2 ); point P3 = p1 + P2; cout <p3.get _ x () <"" <p3.get _ y () <Endl; return 0 ;}

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.