Use of C ++ and objects (1). Use of Objects

Source: Internet
Author: User

Use of C ++ and objects (1). Use of Objects

Object initialization

It is wrong to initialize the data member directly when declaring the class! The following example is incorrect !!

 

Class Time {hour = 0; minitu = 0; sec = 0;} // because a class is not an entity, it is an abstract type and does not occupy storage space, obviously, data is nowhere to be accommodated;

 

If all the members in a class are of the public type, you canWhen defining an objectInitialize data members.

Class Time {public:
Hour; minitu; sec;}; Time t1 = {13, 12, 40}; // similar to the initialization Member of the struct, but limited to public data members

  Use constructors to initialize data members

C ++ provides constructors to process object initialization. Constructor is a special member function. Unlike other member functions,You do not need to call it. Instead, it is automatically executed when an object is created.; The constructor name must be the same as the class name. It does not have any type or return value;

1) define constructors in the class

class Time{public: Time(){         hour =0;         minitu=0;         sec=0;         }} Time t1={13,12,40};

2) declare in the class and define outside the class

Class Time {public: Time (); // declare constructor} Time: time () {hour = 0; minute = 0; sec = 0 ;}

The following describes how to use constructors:

1) When will the constructor be called? The constructor is automatically called when an object is created. When an object is created, a storage unit is assigned to the object. When the constructor is executed, the specified initial value is sent to the storage unit of the relevant data member. Each time an object is created, the sequential constructor is called.

2) The constructor has no return value or type, but only initializes the object.

3) constructors are neither called nor called by users.

4) You can use one class object to initialize another object.

Time t1; // create object t1, call the constructor t1.Time () Time t2 = t1 at the same Time; // create object t2, and call a t1 to initialize t2

In this case, copy the values of data members of object t1 to corresponding members of object T2. the constructor t2.Time () is not called ();

5) in the constructor function body, you can not only assign initial values to data members, but also include other statements, such as cout statements, which are generally not recommended.

6) if the user does not define a constructor, the system will automatically generate a constructor. The constructor only has space-time and no parameters and does not perform initialization;

 Constructors with Parameters

Sometimes users want to assign different initial values to different objects, so they need to consider constructors with parameters. When calling constructor of different objects, different data is transmitted from the outside to the constructor for different initialization. The constructor header is generally in the following format:

Constructor name (parameter 1, parameter 2 ,......)

Real parameters must be provided when defining an object. The general format of the defined object is:

Class Name Object Name (real parameter 1, real parameter 2 ,......)

# Include <iostream> using namespace std; class Box {public: Box (int, int, int); // declare int volume (); private: int height; int width; int length;}; Box: Box () // out-of-class definition {height = h; width = w; length = len;} int Box: volume () {return (height * width * length);} int mian () {Box box1 (, 48); // create the box1 object and provide the cout parameter <"the box2 is: "<box2.volume () <endl; return 0 ;}

1) the parameters in the constructor with parameters are specified when the object is created. That is, when an object is created, the initial value of the data member is specified.

2) The real parameters used to define different objects are different. They reflect the properties of different objects. This method can be used to easily initialize different objects.

  Initialize a table with parameters for data members

The following form can be used to define constructors:

Class Name: constructor name ([parameter table]) [: Member initialization table] {[constructor body]} // optional (optional) in square brackets)

Box::Box(int h,int w,int len):height(h),width(w),length(len){}

Overload of Constructors

You can define multiple constructors in a class to provide different initialization methods for objects. These constructors have the same name, and the number or type of parameters are different, which is called the overload of the constructor.

# Include <iostream> using namespace std; class Box {public: Box (); Box (int h, int w, int len): height (h), width (w ), length (len) {} int volume (); private: int height; int width; int length ;}; Box: Box () {height = 10; width = 10; length = 10;} int Box: volume () {return (height * width * length);} int mian () {Box box1; // create an object box1, cout <"the box1 is:" <box1.volume () <endl; Box box2 (14,12, 48); cout <"the box2 is: "<box2.volume () <endl; return 0 ;} /// // Box: Box (int h) Box :: box (int h, int w)

1) A constructor with real parameters is not required when an object is created. It is called a default constructor. Obviously, a non-argument constructor belongs to the default constructor. A class can have only one default constructor.

2) When creating an object, you should use a non-argument constructor. Be sure to correctly write the statements defining the object. Constructors cannot be explicitly called by users.

3) Although a class can contain multiple constructors, only one of them is executed when an object is created.

  Constructor using default parameters

The values of parameters in the constructor can be passed through real parameters, or some default values can be located. That is, if you do not specify real parameter values, the default values of parameters are used in the compilation system.

#include<iostream>using namespace std;class Box{public:    Box(int h=10,int w=10,int len=10);    int volume(); private:     int height;     int width;     int length;};Box::Box(){    height=h;    width=w;    length=len;}int Box::volume(){    return(height*width*length);}int mian(){    Box box1;    cout<<"the box1 is:"<<box1.volume()<<endl;        Box box2(14,12);    cout<<"the box2 is:"<<box2.volume()<<endl;    Box box3(14,12,48);    cout<<"the box3 is:"<<box3.volume()<<endl;    return 0; } 

Note:

1) Where should I specify the default parameters of the constructor?You should specify the default value when declaring the constructor, instead of specifying the default value when defining the constructor.Because the declaration is placed in the header file, it is the external interface of the class.

2) the fifth line is equivalent

Box (int = 10, int = 10, int = 10); // Save the parameter name

3) If all parameters of the constructor specify the default value, one or several real parameters can be provided or no real parameters can be provided when the object is defined. A constructor can be called without parameters. One class can have only one constructor.The following is an error !!

    Box();    Box(int=10,int=10,int=10);

4) after a constructor with all default parameters is defined in a class, the overload constructor cannot be defined.

Box (int = 10, int = 10, int = 10); Box (int, int); if the following statements are defined: Box box1; // is the first or second constructor called above ?? Box box2 (); // is the first or third constructor called above ??

If:

Box (); Box (int = 10, int = 10, int = 10); Box (int, int); if the following statements are defined: Box box1; // correct, call the first Box box2 (12); // correct. Call the second Box box3 (12, 89); // error, with Ambiguity

 

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.