拷贝构造函数

来源:互联网 发布:西安美林数据是外包吗 编辑:程序博客网 时间:2024/06/15 11:58
//头文件kaobei.hclass CExample{public:CExample(){pBuffer=NULL;nSize=0;} //构造函数~CExample(){delete [] pBuffer;} //析构函数CExample(const CExample&); //拷贝构造函数void Init(int n){pBuffer=new char[n];nSize=n;}private:char *pBuffer; //类的对象中包含指针,指向动态分配的内存资源int nSize;};CExample::CExample(const CExample& RightSides) //拷贝构造函数的定义{nSize=RightSides.nSize; //复制常规成员pBuffer=new char[nSize]; //复制指针指向的内容memcpy(pBuffer,RightSides.pBuffer,nSize*sizeof(char));}//.cpp文件#include "iostream"#include "kaobei.h"using namespace std;int main(int argc,char* argv[]){CExample theObjone;theObjone.Init(40);CExample theObjtwo=theObjone;}