Everything-heavy load (re-transfer)

Source: Internet
Author: User
Comprehensive
---- Overload
Author: HolyFire
All-in-one is that many aspects have been taken into account. Sometimes our sentence applies to many aspects, and these aspects are similar. For example, an addition can be used for integers and rational numbers. In C ++, two functions can be used for this purpose.
Int intadd (int v1, int v2)
{
Return v1 + v2;
}
Float floatadd (float v1, float v2)
{
Return v1 + v2;
}
The method is as follows:
Int ia = 1, ib = 2, iab = 0;
Float fa = 1.0, fb = 2.0, fab = 0.0;
Iab = intadd (ia, ib );
Fab = floatadd (fa, fb );
This looks unintuitive and has poor readability. Our goal is to let people see at a glance that they are doing addition operations.
Smart readers may find that the return values and parameters of two functions are not the same, so that two different behaviors can be differentiated. Can this feature be used? The answer is yes. C ++ has done everything for us. The principle is very simple. The return values and parameters of a function are converted into a string using a reversible encoding method, which is placed after the function name. The compiler shields users from all this, you can use different functions with the same name.
That's it.
Int add (int v1, int v2)
{
Return v1 + v2;
}
Float add (float v1, float v2)
{
Return v1 + v2;
}
Int ia = 1, ib = 2, iab = 0;
Float fa = 1.0, fb = 2.0, fab = 0.0;
Iab = add (ia, ib );
Fab = add (fa, fb );
Oh ~~~~, After the compilation is passed, the results are also run correctly.
This code looks much better than the original one, so we can skip things we are not interested in.
Another aspect of overloading is that operators can be overloaded. The difference is that it requires a keyword operator. In this way, you can use operators in your own way. So use operators to rewrite everything above.
Int operator + (int v1, int v2)
{
Return v1 + v2;
}
Float operator + (float v1, float v2)
{
Return v1 + v2;
}
Int ia = 1, ib = 2, iab = 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.