C++ explains the default parameters of the constructor and simple example code

  • 2020-05-12 02:58:08
  • OfStack

Now let me introduce you to the constructor with default parameters:

You know that a function gets its arguments from its arguments when it calls a function, so we have to make sure that we have the same number of arguments as we have the same number of arguments. And in some cases we might have a fixed value for the argument. For example, we need to calculate the area length of the rectangle, x width, but the user can not enter the length and if the user specifies, the default length is 3, but if the user specifies, the user specifies the width, which is the default parameter!

Code:


#include <iostream>
using namespace std;
int area(int l,int w=3);//  Function declaration   And define the default parameters w=3 ; 

int main(){
  int c=4; // long 
  int k=5;
  int res; // The results of 
  res = area(c);
  cout<<res<<endl;
  return 0;
}
int area(int l,int w){// The function definitions  l long  w wide 
  int res=0;
  res = l*w;
  return res;
}

For example, in the code above, if we like res=area (c) in line 8; I didn't write res=area (c, w); I don't specify what the width is, so if I write this, I specify that the width of the rectangle is 5; The results are different!

The former is going to be 12
The latter has a demerit score of 20

That's the difference between a function with default parameters and one without;

The following problem sets:

The design function calculates the volume of the cuboid and the area of the rectangle

If the user specifies 3 parameters, calculate the volume of the cuboid. If the user enters 2 parameters, calculate the area of the rectangle!

Take advantage of a constructor with default parameters;

Reference code:


#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
int area(int l,int w,int h=1);//  Function declaration   And define the default parameters w=3 ; 

int main(){
  int c=4; // long 
  int k=5;// wide 
  int h=2;// high  
  int res; // The results of 
  res = area(c,k);
  int res2=area(c,k,h);
  cout<<" Covers an area of  ="<<res<<endl;
  cout<<" The volume of  ="<<res2<<endl;
  return 0;
}
int area(int l,int w,int h){// The function definitions  l long  w wide 
  int res=0;
  res = l*w*h;
  return res;
}

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: