c++--function overloading

Source: Internet
Author: User

C + + allows functions with similar functions to be declared with the same function name within the same scope, resulting in overloading, ease of use, and ease of memory.

/* different form parameter types */ int Add (int x,int  y); float Add (float x,float  y); /* The number of formal parameters is different */ int Add (int x,int  y); int Add (int x,int y,int z);

Precautions:

>> the parameters of an overloaded function must be different: the number is different or the type is different

The >> compiler chooses which function to invoke based on the best match of the type and number of arguments and parameters

/* The compiler does not differentiate by formal parameter names */ int Add (int x,int  y); int Add (int A,int  b); /* The compiler does not differentiate from the return value */ int Add (int x,int  y); void Add (int x,int y);

>> do not declare functions of different functions as overloaded functions in order to avoid misunderstandings and confusion about the result of the call.

int Add (int x,intreturn x +y;} float Add (float x,floatreturn XY;}

Examples of overloaded function applications:

Write two overloaded functions named Sumofsquare, respectively, to find the sum of squares of two integers and the sum of squares of two real numbers.

#include <iostream>using namespacestd;intSumofsquare (intAintb) {    returnA * a + b *b;}DoubleSumofsquare (DoubleADoubleb) {    returnA * a + b *b;}intMain () {intm, N; cout<<"Enter the integer:"; CIN>> m >>N; cout<<"their sum of square:"<< Sumofsquare (M, N) <<Endl; Doublex, y; cout<<"Enter The real number:"; CIN>> x >>y; cout<<"their sum of square:"<< sumofsquare (x, y) <<Endl; System ("Pause"); return 0;}

Output Result:

c++--function overloading

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.