Constructor: Handles initialization of an object, which is a special member function that, unlike other functions, does not require the user to invoke it and is executed automatically when the object is created.
Note :(1) each time an object is created, a constructor is called;
(2) The constructor does not have a return value, so there is no type, and the function is to initialize the object only;
(3) constructors do not need to be called by the user, nor can they be called by the user.
Overloading of constructors: constructors have the same name, and the number of arguments or parameter types are different.
Example 1 Write an object-based program that initializes the data member with a constructor with parameters in the class, seeking the volume of the Fang.
Solution : Program:
#include <iostream>
using namespace Std;
Class Box
{
Public
Box (int, int, int);
int volume ();
Private
int height;
int width;
int length;
};
Box::box (int h,int w,int len)
{
Height = h;
width = w;
Length =len;
}
int Box::volume ()
{
return (height*width*length);
}
int main ()
{
Box box1 (12,25,30);
cout << "The volume of Box1 is:" << box1.volume () << Endl;
Box Box2 (15, 30, 21);
cout << "The volume of Box2 is:" << box2.volume () << Endl;
System ("pause");
return 0;
}
Results:
The volume of Box1 is:9000
The volume of Box2 is:9450
Please press any key to continue ...
Example 2 defines two constructors, one of which has parameters, one without parameters, to find the volume of a long Fang.
Solution: Create an ObjectBox1, no parameter is given, and the system finds the corresponding parameterless constructorBox,The result of executing this constructor is to make the3values for each data member areTen, and then outputBox1the volume of a building objectBox2, give3parameter, the system finds a3constructor for a formal parameterBox,The result of executing this constructor is to make the3the value of a data member is the,30,25, and then outputBox2the volume.
Program:
#include <iostream>
using namespace Std;
Class Box
{
Public
Box ();
Box (int h, int w, int len): Height (h), Width (w), Length (len) {}
Defines an argument constructor that initializes a data member with the initialization list of parameters.
int volume ();
Private
int height;
int width;
int length;
};
Box::box ()//define non-parametric constructors outside the class Box
{
Height = 10;
width = 10;
length = 10;
}
int Box::volume ()
{
return (height*width*length);
}
int main ()
{
Box Box1;
cout << "The volume of Box1 is:" <<box1.volume () <<endl;
Box Box2 (15,30,25);
cout << "The volume of Box2 is:" << box2.volume () << Endl;
System ("pause");
return 0;
}
Results:
The volume of Box1 is:1000
The volume of Box2 is:11250
Please press any key to continue ...
This article is from the "Rock Owl" blog, please be sure to keep this source http://yaoyaolx.blog.51cto.com/10732111/1754910
Definition of constructors and overloading of constructor functions