浅复制:
深复制
/*
** 在C++中,存在浅复制和深复制,浅复制仅仅将内部数据的值拷贝一份
*/
#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;
class Demo
{
private:
char *buffer;
public:
Demo(const char *str);
Demo(const Demo & copy);
~Demo();
Demo & operator=(const Demo & CopyDemo);
void print(void);
};
Demo::Demo(const char *str)
{
if (str!=NULL)
{
buffer = new char [strlen(str)+1];
strcpy(buffer,str);
}
else
buffer = NULL;
}
Demo::Demo(const Demo & copy)
{
if (copy.buffer != NULL)
{
buffer = new char [strlen(copy.buffer)+1];
strcpy(buffer,copy.buffer);
cout<<"Copy Call"<<endl;
}
else
buffer = NULL;
}
Demo::~Demo()
{
if (buffer!=NULL)
{
delete [] buffer;
cout<<"Delete Call"<<endl;
}
}
void Demo::print()
{
cout<<buffer<<endl;
}
/* 重载赋值符号,下面左边的 & 不能漏,否则不影响原来的值 */
Demo & Demo::operator=(const Demo & CopyDemo)
{
if (CopyDemo.buffer!=NULL)
{
buffer = new char [strlen(CopyDemo.buffer)+1];
strcpy(buffer,CopyDemo.buffer);
cout<<"Operator = Call"<<endl;
}
else
buffer = NULL;
}
void Copy(Demo CopyDemo)
{
CopyDemo.print();
cout<<"Call"<<endl;
}
int main()
{
Demo demo("Hello");
Copy(demo); //调用赋值构造函数进行深度复制
demo.print();
cout<<endl;
Demo t("H");
temp = demo; //由于t存在,所以调用赋值运算符重载函数
temp.print();
cout<<endl;
Demo temp = demo; //由于temp不存在,所以调用复制构造函数
return 0;
}