c++拷贝构造函数的问题 http://cache.baidu.com/c?word=%BF%BD%B1%B4%3B%B9%B9%D4%EC%3B%BA%AF%CA%FD&url=http%3A//www%2Evckbase%2Ecom/document

#include "stdafx.h"

 

//class Person{
//private :
// char* _name;
//public :
// Person(){ _name = new char[256];}
//
//};
class CExample
{
public:
 CExample(){pBuffer=NULL; nSize=0;}
 ~CExample(){delete pBuffer;}
 CExample(const CExample&); //拷贝构造函数
 void Init(int n){ pBuffer=new char[n]; nSize=n;};
 CExample& operator = (const CExample&); //赋值符重载

private:
 char *pBuffer; //类的对象中包含指针,指向动态分配的内存资源
 int nSize;
};
CExample::CExample(const CExample& RightSides) //拷贝构造函数的定义
{
 nSize=RightSides.nSize; //复制常规成员
 pBuffer=new char[nSize]; //复制指针指向的内容
 memcpy(pBuffer,RightSides.pBuffer,nSize*sizeof(char));
}
//int main(){
//
// return 0;
//}
 //int main(int argc, char* argv[])
 //{
 // CExample theObjone;
 // theObjone.Init(40);

 // //现在需要另一个对象,需要将他初始化称对象一的状态
 // CExample theObjtwo=theObjone;
 // //...
 //}
//赋值操作符重载
CExample & CExample::operator = (const CExample& RightSides)
{
 nSize=RightSides.nSize; //复制常规成员
 char *temp=new char[nSize]; //复制指针指向的内容
 memcpy(temp,RightSides.pBuffer,nSize*sizeof(char));

 delete []pBuffer; //删除原指针指向内容  (将删除操作放在后面,避免X=X特殊情况下,内容的丢失)
 pBuffer=temp;   //建立新指向
 return *this;
}

 int main(int argc, char* argv[])
 {
  CExample theObjone;
  theObjone.Init(40);

  CExample theObjthree;
  theObjthree.Init(60);

  //现在需要一个对象赋值操作,被赋值对象的原内容被清除,并用右边对象的内容填充。
  theObjthree=theObjone;
  return 0;
 }
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值