Copy the knowledge of constructor and value assignment function, and copy the constructor value assignment.

Source: Internet
Author: User

Copy the knowledge of constructor and value assignment function, and copy the constructor value assignment.

/****************** There are two differences between the copy constructor and the value assignment operator overloading ******** *******************/

 

1. Copy the constructor to generate a new class object, but the value assignment operator cannot.

2. since the copy constructor directly constructs a new class object, you do not need to check whether the source object is the same as the new object before initializing this object. The copy operator needs this operation, in addition, if there is memory allocation in the original object in the assignment operator, you must first release the memory.

The following is an implementation function of the String class. We can see the difference between them.

1 class String {2 public: 3 String (const char * str = NULL); 4 String (const String & other); 5 ~ String (); 6 String & operator = (const String & other); 7 private: 8 char * m_data; 9}; 10 11 String: String (const char * str) {12 if (str! = NULL) {13 int length = strlen (str); 14 m_data = new char [length + 1]; 15 strcpy (m_data, str); 16} 17} 18 19 String: :~ String () {20 delete m_data; 21} 22 23 String: String (const String & other) {24 int length = strlen (other. m_data); 25 m_data = new char [length + 1]; 26 assert (m_data! = NULL); 27 strcpy (m_data, other. m_data); 28} 29 30 String & String: operator = (const String & other) {31 if (this = & other) {// determine whether to assign a value to yourself 32 return * this; 33} 34 if (m_data! = NULL) {// check whether the memory is allocated 35 delete m_data; 36} 37 int length = strlen (other. m_data); 38 m_data = new char [length + 1]; 39 assert (m_data = NULL); 40 strcpy (m_data, other. m_data); 41 return * this; 42}

 

************* ******/

 

#include<iostream>#include<assert.h>using namespace std;class B{public:    B():data(0){        cout << "default constructor" << endl;    }    B(int i):data(i){        cout << "constructed by parameter " << data << endl;    }    B (B &b){        data = b.data;        cout << "copyed by parameter " << data << endl;    }    B & operator=(const B& b){        this->data = b.data;        cout << "=     by parameter " << data << endl;        return *this;    }private:    int data;};

void test(){
    B b1;
    B b2 = b1;
    B b3;
    b3 = b1;
}int main(){

  test(); system("pause"); return 0;}

The test () function and system ("pause") function are used to avoid exiting the main function. You can see that the Destructor is executed. Run the command to obtain the following results.

Default constructor
Copyed by parameter 0
Default constructor
= By parameter 0

Take a closer look at the code segment in the test function.

B2 calls the copy constructor, while b3 calls the value assignment function. The two are different.

 

/******************** About the temporary object of the copy constructor and the value assignment function ******* ***********************/

 

See the following code to see what the output will be.

 1 #include<iostream> 2 #include<assert.h> 3 using namespace std; 4  5 class B{ 6 public: 7     B():data(0){ 8         cout << "default constructor" << endl; 9     }10     ~B(){11         cout << "destructed by parameter " << data << endl;12     }13     B(int i):data(i){14         cout << "constructed by parameter " << data << endl;15     }16     B (B &b){17         data = b.data;18         cout << "copyed by parameter " << data << endl;19     }20     B & operator=(const B& b){21         this->data = b.data;22         cout << "=     by parameter " << data << endl;23         return *this;24     }25 private:26     int data;27 };28 29 B play(B b){30     return b;31 }32 33 void test(){34     play(1);35     B t1 = play(2);36     B t2;37     t2 = play(3);38 }39 40 int main(){41 42     test();43     system("pause");44     return 0;45 }


This program adds a play () function and the output of the destructor to the previous one. After seeing the output results, I have some questions. The output result is as follows. Numbers are provided for convenience.

(1) constructed by parameter 1
(2) copyed by parameter 1
(3) destructed by parameter 1
(4) destructed by parameter 1
(5) constructed by parameter 2
(6) copyed by parameter 2
(7) destructed by parameter 2
(8) default constructor
(9) constructed by parameter 3
(10) copyed by parameter 3
(11) destructed by parameter 3
(12) = by parameter 3
(13) destructed by parameter 3
(14) destructed by parameter 3
(15) destructed by parameter 2

If you have any questions, you can first understand the following three points.

 

1. if a target object is constructed from the source object of the same class, a copy constructor is called to construct the target object. If no copy constructor is defined, the default copy function is called to construct the target object.

2. When a class has a constructor with a parameter, you can use the data of the same type as this parameter to initialize this object. By default, this constructor is called.

3. when the return value of a function is a class object, if an object is not defined to receive the returned value in the call function (which is called rather than called, A temporary object is returned to save the value of the returned object. When the called function ends, the temporary object is destroyed. When there is a receiving object, the returned object is assigned to the receiving object, which calls the Destructor at the end of the function call (note that the function is called.

 

The first point is embodied in the 35 lines of the program. As mentioned above, it will call the copy constructor instead of the value assignment function.

The second point is embodied in 34 rows. The type of play (1) is integer, and Class B has a constructor with the int type. When the real parameter 1 is passed to the form parameter B, will call this constructor.

The third point is 34 rows and 37 rows. The play (1) function is called and a class object is returned. At this time, no object is received (the assignment is accepted on the left side), so a temporary object is returned, the temporary object is destroyed by calling the Destructor when the function play is called. Output (4) destructed by parameter 1; t2 = play (3); play (3) in the statement) called, an object is returned, and an object (t2) is received at this time, so the value assignment function is called and assigned to t2. When the function (test) is called, this object is destroyed and output (13) destructed by parameter 3.

 

Therefore, the output meanings are as follows:

Constructed by parameter 1 // use 1 to construct parameter B
Copyed by parameter 1 // use B to construct a temporary object
Destructed by parameter 1 // The structure of parameter B is analyzed.
Destructed by parameter 1 // The structure of the temporary object is
Constructed by parameter 2 // use 2 to construct parameter B
Copyed by parameter 2 // use B to construct t1
Destructed by parameter 2 // The structure of parameter B is analyzed.
Default constructor // construct t2
Constructed by parameter 3 // use 3 to construct parameter B
Copyed by parameter 3 // use B to copy a temporary object
Destructed by parameter 3 // The structure of parameter B is analyzed.
= By parameter 3 // call the value assignment function = () to initialize t2
Destructed by parameter 3 // The structure of the temporary object is
Destructed by parameter 3 // structure of t2
Destructed by parameter 2 // t1 destructor


The differences between the copy constructor, constructor, and the value assignment statement

Differences between a copy constructor and a value assignment function blog.csdn.net/...804908
Differences between copy constructors and constructors blogold.chinaunix.net/u3/94667/showart_2244350.html
 
What is the value assignment function in C ++? Why can there be more Constructors?

Haha, basic knowledge is generally introduced in C ++ books.
There are several constructor types: Let me talk about the class named.
1. default constructor. It is called by default when the object of A is created (if there are no other constructor)
2. Copy the constructor and use an object of Class A to initialize another class A object.
4. The value assignment function is used to assign values between objects.
5. Define other constructors by yourself.

Above 1 ~ The three constructors in 3 are built in by default for each C ++ class, even if you do not declare them.
The following is an example.
Class {
Public:
A () {}// default constructor, nothing to do
A (int I) {m_ I = I;} // custom constructor. Use int variable I to initialize class A Object member m_ I
A (A & a) {m_ I =. m_ I;} // copy the constructor, which generally does not need to be overloaded. The function is to copy all the internal members of the parameter object to the new object.
A & operator = (const A & a); // The Value assignment function is not A constructor, but an operator overload. Assign values to the current object using the form parameter object
A & operator = (const int I); // another overloaded value assignment function. I is used to assign values to Class A objects.
~ A (){}
Public:
Int m_ I;
};

A & A: operator = (const A &)
{
This. m_ I = a. m_ I;
Return * this;
}

A & A: operator = (const int I)
{
This. m_ I = I;
Return * this;
}

The following is an example of an application.
A a; // call the default constructor
A. m_ I = 100; // assign values to members of.
A B (a); // call the copy constructor and use object a to initialize object B. Then, the m_ I of object B is changed to 100.
A c;
C = B; // call the value assignment function and assign values to c using object B. The default value assignment function is similar to the copy constructor function.
C = 200; // call the custom value assignment function. Use 200 to assign values to m_ I OF THE c object.
A d (150); // calls A custom constructor and assigns A value to m_ I OF THE d object using 150.

The above is the code I am writing on a temporary basis. The level is limited. If not, please criticize and correct the code.

Related Article

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.