[C++ Study Notes]: Constructor overloading

C++ uses parameter initialization table to initialize data members

In C++, the function of the constructor can initialize the data members through the assignment statement in the body. C++ also provides another method of initializing the data members, using the parameter initialization table to initialize the data members.

This method does not initialize the data members in the function body, but is implemented in the function header. For example, the constructor can be defined in the following form: 

Box::Box(int hgt,int wid,int len):height(hgt),width(wid),length(len){}

This writing method is very concise, especially when there are many data members that need to be initialized, you can even define the constructor directly in the class body. 

C++ constructor with default parameters

The values ​​of the parameters in the constructor can be passed through actual parameters or specified as some default values. That is, if the programmer does not specify the actual parameter values, the compilation system will make the formal parameters take the default values. 

C++ constructor overloading

Overloading means that multiple constructors can be defined in a class to provide different initialization methods for class objects for programmers to choose. These constructors have the same name, but the number or type of parameters are different. .

Case: To find the volume in C++, overloading is required.

#include<iostream>//Preprocessing
using namespace std;//Namespace
class Box
{   public: //Declare public   Box(); //No-parameter constructor   Box(int,int,int);//Construction with parameters Function   int volume();//Declare the volume function   private: //Declare private   int height;//Define height   int width; //Define width   int length; //Define length }; Box::Box()//In Define a parameterless constructor outside the class {   height=10;   width=10;   length=10; } int Box::volume()//Define the volume function {   return height*width*length; //Length times width times height } int main()//Main function {   Box box;// Create object box, no parameter   cout<<"The volume of the cylinder is:"<<box.volume()<<endl;   return 0; //The function return value is 0;
























}

Compile and run results:

The volume of the cylinder is: 1000

--------------------------------
Process exited after 0.08839 seconds with return value 0
Please press any key continue. . .

Guess you like

Origin blog.csdn.net/Jiangziyadizi/article/details/129538879