当前位置:网站首页>15. copy constructor

15. copy constructor

2022-06-13 08:50:00 zzyzxb

#include “Time.h”

//void func(Time tmptime)
//{
// return;
//}

Time func()
{
Time linshitime;
return linshitime;
}

int main()
{
// One : copy constructor ( copy constructor )
//int a = 3;
//int b = a; // The act of ordinary copying
// By default , The copy of a class object is to copy each member variable one by one ;
// If the constructor of a class , The first parameter of is the reference of the class type to which it belongs , If there are other additional parameters ,
// Then these additional parameters have default values , Then this constructor is called the copy constructor .
// Function default arguments must be placed in the function declaration , Unless The function has no function declaration
// The function of the copy constructor : At a certain time , Automatically called by the system .
//(1) It is recommended that the first parameter of the copy constructor always carry const
//(2) explicit: Copy constructors are generally not declared as explicit.

// The function of copying member variables one by one is lost because of the existence of our own defined copy constructor 
// Or our own " copy constructor " Instead of the default behavior of copying each member variable one by one 

//a) If we don't define a copy constructor for the class , The compiler will help us define a " Composite copy constructor ".
//b) If the compiler gives us the synthesized copy constructor , This synthetic copy constructor is also generally used to tmptime Copy each member of to the object being created .
// The type of each member determines how it is copied , For example, if the member variable is an integer , Then copy the value directly .
//c) If you define a copy constructor yourself , Instead of the copy constructor for system composition , This is the time , You have to assign values to class members in your own copy constructor 
// To avoid the use of class members without assignment 

//Time myTime; // This will call the default constructor ( With no arguments )
//Time myTime2 = myTime; // Called copy constructor  
//Time myTime3(myTime); // Called copy constructor 
//Time myTime4{ myTime }; // Called copy constructor 
//Time myTime5 = { myTime }; // Called copy constructor 
//Time myTime6; // This will call the default constructor ( With no arguments )
//myTime6 = myTime5;


// There are also cases where a copy constructor is called 
// (1) Pass an object as an argument to a formal parameter of a non reference type 
//func(myTime);
// (2) When returning an object from a function 
Time mytime = func();

}

原网站

版权声明
本文为[zzyzxb]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202270536495814.html