#include <iostream></p> #include <string>using namespace Std;class name{public:name ();//default constructor name (char *PN); Constructor name (const name &obj);//Copy Constructor ~ name ();//destructor Protected:char *pname; int size;p ublic:name& operator= (name &obj);//"=" operator overloading}; Name::name () {cout<< "Constructing" << endl;pname=null;size=0;} Name::name (char *pn) {cout << "constructing" << pn << Endl; PName = new Char[strlen (PN) +1]; if (pname) strcpy (PNAME,PN); size = strlen (PN);} Name::name (const name &obj) {cout << "copy constructing" <<obj.pname<<endl;pname = new Char[strlen (obj.pname) +1];if (pname) strcpy (pname,obj.pname); size = strlen (obj.pname);} name& name::operator= (name &obj) {cout << "assigning" <<obj.pname<<endl;if (This==&obj) The this pointer is used to represent the address of the current object {return obj;} if (pname) {delete []pname;size=0;} PName = new Char[strlen (obj.pname) +1];if (pname) {strcpy (pname,obj.pname); Size=strlen (obj.pname);} return *this;} Name::~ name () {cout << "destructing" << pname << Endl; Delete []pname;size = 0;} void Playmain () {Name obj1 ("Zhangsan");//If you do not write the copy constructor, then the C + + compiler will give us a default copy constructor (light copy) name obj2 = Obj1;name obj3 (" Lisi "); name obj4;//If you do not write = Operation function, then the C + + compiler will give us a = Operation function (shallow copy) Obj4=obj3;} void Main () {playmain (); System ("Pause");}
In C + +, the following three objects require a call to the copy constructor (sometimes referred to as a "copy constructor"):
1) An object is passed into the function body as a function parameter in the way of value passing;
2) An object is returned from the function as a function return value, in the way that the value is passed;
3) An object is used to initialize another object (often referred to as assignment initialization);
Reprint Please specify source: http://blog.csdn.net/lsh_2013/article/details/45457739
Copy constructor of C + +