拷贝构造函数,是一种特殊的构造函数,它由编译器调用来完成一些基于同一类的其他对象的构建及初始化。其唯一的形参必须是引用,但并不限制为const,一般普遍的会加上const限制。此函数经常用在函数调用时用户定义类型的值传递及返回。拷贝构造函数要调用基类的拷贝构造函数和成员函数。如果可以的话,它将用常量方式调用,另外,也可以用非常量方式调用
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 |
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceC_Sharp_structVSclass{classMyClass{publicintval;}structmyStruct{publicintval;}classProgram{staticvoidMain(string[]args){MyClassobjectA=newMyClass();MyClassobjectB=objectA;objectA.val=10;objectB.val=20;Console.WriteLine("{0}",objectA.val);Console.WriteLine("{0}",objectB.val);Console.ReadKey();}}} |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 |
classCExample{public:CExample(){pBuffer=NULL;nSize=0;}~CExample(){delete[]pBuffer;}voidInit(intn){pBuffer=newchar[n];nSize=n;}private:char*pBuffer;//类的对象中包含指针,指向动态分配的内存资源intnSize;};这个类的主要特点是包含指向其他资源的指针,pBuffer指向堆中动态分配的一段内存空间。intmain(intargc,char*argv[]){CExampletheObjone;theObjone.Init(40);//现在需要另一个对象,并将它初始化为theObjoneCExampletheObjtwo=theObjone;...} |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 |
classCExample{public:CExample(){pBuffer=NULL;nSize=0;}~CExample(){delete[]pBuffer;}CExample(constCExample&);//拷贝构造函数voidInit(intn){pBuffer=newchar[n];nSize=n;}private:char*pBuffer;//类的对象中包含指针,指向动态分配的内存资源intnSize;};CExample::CExample(constCExample&RightSides)//拷贝构造函数的定义{nSize=RightSides.nSize;//复制常规成员pBuffer=newchar[nSize];//分配内存memcpy(pBuffer,RightSides.pBuffer,nSize*sizeof(char));} |
|
1
2
3
4
5
6
7
8
9
10 |
intmain(intargc,char*argv[]){CExampletheObjone;theObjone.Init(40);CExampletheObjthree;theObjthree.init(60);//现在需要一个对象赋值操作,被赋值对象的原内容被清除,并用右边对象的内容填充。theObjthree=theObjone;return0;} |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 |
classCExample{public:CExample(){pBuffer=NULL;nSize=0;}~CExample(){deletepBuffer;}CExample(constCExample&);//拷贝构造函数CExample&operator=(constCExample&);//赋值符重载voidInit(intn){pBuffer=newchar[n];nSize=n;}private:char*pBuffer;//类的对象中包含指针,指向动态分配的内存资源intnSize;};//赋值操作符重载CExample&CExample::operator=(constCExample&RightSides){if(this==&RightSides)//如果自己给自己赋值则直接返回{return*this;}nSize=RightSides.nSize;//复制常规成员char*temp=newchar[nSize];//复制指针指向的内容memcpy(temp,RightSides.pBuffer,nSize*sizeof(char));delete[]pBuffer;//删除原指针指向内容(将删除操作放在后面,避免X=X特殊情况下,内容的丢失)pBuffer=temp;//建立新指向return*this;} |
原文地址:http://www.cnblogs.com/cqwyj2000/p/3754425.html