C++ copy constructor code example



C++ copy constructor code example

JAVA;">

#include

 

  

class CFrist

{

    int data;

public:

    CFrist(int d=0)//constructor

    {

        data=d;

    }

    CFrist(CFrist &timp)//copy construction function

    {

        data=timp.data;

    }

    /*1. It is the same as the constructor, but the parameters are unique. If you do not write the

   system, a default copy constructor will be given, and the corresponding members will be assigned values;


    2. And here must use the reference, can not directly pass the value. Passing an object by a function will call the copy constructor (detailed below),

    so if you pass in an object when calling the copy constructor, the copy constructor will be called again, and the loop will go on forever.


    3. The copy constructor is called when an object is assigned to an object when an object is constructed, and is not called when a simple assignment is made.

    */

    ~CFrist(){}

};

CFrist text(CFrist t5)

{/*The function passes parameters and passes in an object, the function will *construct the t5 object and assign the passed-in object to t5*, which is consistent with the construction and assigning the object at the same time, and the copy constructor will be performed*/

    CFrist timp;

    timp=t5;

    return timp;

    /* The scope of timp is only in this function.

    When he returns, he * constructs a temporary object, and assigns timp to the temporary object *, which is in line with the assignment of objects at the same time of construction, just A copy will be done after the constructor function

    ends and the timp is released

    and the temporary object is used as the return value and assigned to the place where the function is called*/

}

int main()

{

    CFrist t1(10);//The constructor initializes

    CFrist t2 =t1;//Construct the object and initialize it at the same time; call the copy constructor;

    CFrist t3(t1);//Same as above

    CFrist t4;//Constructor initialization

    t4=t1;//Assignment statement, the copy constructor will not be executed;

    //Indicate that the copy constructor is only called when the value is assigned during initialization. It will not be called when other objects assign objects;


    // Then when is there a situation where an object is initialized and an object is assigned?

    //that's when the function's call and return value is an object;

    t4=text(t1);

}

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326470758&siteId=291194637