Default parameters for C + + functions

Source: Internet
Author: User

Default parameters of a common function

# include<iostream>using namespace std;void func (int m=0,int n=1)//m=0, called the function's default parameter, is also called the default parameter. The default parameter can have one or more. {cout<< "M:" <<m<< "\ T" << "N:" <<n<<endl;} int main () {func (); func (3,5);//When the function is called, the default argument is called when there are no arguments, and if there are arguments, the parameters prevail. return 0;}

Operation Result:


Second, the default parameters of the member function

# include<iostream>using namespace Std;class a{public:void set (int =20,int =3);//It is permissible to write. void Count (bool=false);p rivate:int w;int h;}; int main () {A a;cout<< "when using the default function:" <<endl;a.set (); A.count (); A.count (true);cout<<endl<< " When re-copying: "<<endl;a.set (5,2);    A.count (); A.count (true);//So the default function also implements the overloaded function. return 0;} void A::set (int width,int height) {w=width;h=height;} void A::count (bool val) {if (val==true) {cout<< "Val value is true:" <<W*H<<ENDL;} elsecout<< "Val value is false:" <<W*H/2<<ENDL;}

Operation Result:


Comments:

1, the overloaded function is easy to use and easy to understand. The function of the default parameter is easily ignored if it is not labeled, and is easily overwritten by a function with the same name as the parameter.

2. A function overloaded with a default parameter is the numeric value of the parameter, and the overloaded function overloads the type of the parameter.

Default parameters for C + + functions

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.