1. Special Constructors
  |
copy constructor |
|
Constructors without parameters |
Const Class_name& constructor |
|
when a constructor is not defined in a class , the compiler defaults to provides an parameterless constructor , and its function body is empty |
when a copy constructor is not defined in a class , the compiler provides a copy constructor by default, simple copy of the value of the member variable |
Special constructors for "programming experiments"
2. Copy Constructors
(1) Meaning of copy constructor function
① is a C-compatible initialization method that uses existing objects to create new objects. (because initialization in C + + involves the invocation of a copy constructor.) Note that initialization is different from assignment, and the "=" operator is called when the value is assigned)
such as: int a = b; C, one variable is used to initialize the other variable;
Student s2 = s1;//is initialized with existing S1 objects, much like the initialization of C
② initialization behavior that conforms to the expected logic
(2) Shallow copy and deep copy
① the physical state of the object after the copy is the same → the copy constructor provided by the compiler is only shallow copy
② the logical state of the object after copying
Initialization of the "Programming Experiment" object
(3) When a deep copy is required
A member of the ① object refers to a resource in the system
② if a member points to a dynamic memory space , opens a file in external memory , or uses a network Port in the system, etc.
③ a custom copy constructor , it is necessary to implement a deep copy
Improvement of the "Programming Experiment" array class
3. Summary
(1) The C + + compiler will provide constructors by default
(2) The parameterless constructor is used to define the default initial state of the object
(3) Copy constructor copies the state of an object when it is created
(4) The copy of the object has a shallow copy and a deep copy of two ways
Construction of the 19th lesson object (bottom)