There's no escaping the pit. Default parameters for--c++ functions (redefine default parameters)

Source: Internet
Author: User

The default parameter refers to the automatic use of a value when an argument is omitted from a function call.

The first thing to note here is:
for a function with a parameter list, you must add a default value from right to left.
That is, to set a default value for a parameter, you must provide a default value for all parameters to the right of it.

The pit that I met today is that the function uses the default parameters, and the declaration and definition of the function are separate.

char* left(constcharstrint n=1);int main(){}char* left(constcharstrint1)//错误{}

The above code can be modified in two ways:

1 declaration with default parameters, no default value when implemented

char* left(constcharstrint n=1);int main(){}char* left(constcharstrint n ){}

2 implemented with default parameters, no default value declared

char* left(constcharstrint n);int main(){}char* left(constcharstrint1){}

There is a mistake that we often make.
In many cases, we can use default parameters instead of function overloads:

void point(int,int){//...}void point(int a){return point(a,4);}void point(){return point(3,4);}

You can use the following function to override the default parameters:

void point(int=3,int=4);

Called Point (3,4) when a "point ();" is called, which is the 3rd overloaded function declared.
When a "point (6);" is called, it is called "point (6,4);", which is the 2nd overloaded function declared.
An overloaded function that calls the 1th declaration when "Point (7,8);" is called

When you are happy, if a set of overloaded functions (which may have default parameters) allows the same number of calls, it will cause the two semantics of the call.
    

func(int//重载函数之一func(int,int=4//重载函数之二,带有默认参数func(int=3,int=4//重载函数之三,带有默认参数func(7//error: 到底调用3个重载函数中的哪个?func(20,30//error:到底调用后面2个重载函数的哪个?

There's no escaping the pit. Default parameters for--c++ functions (redefine default parameters)

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.