您的位置:首页 > 编程语言 > C语言/C++

C++浅层与深层复制构造函数

2014-03-14 22:16 197 查看
//浅层复制构造函数代码
#include<iostream>
using namespace std;
class Test
{
public:
Test()
{
x=new int;
*x=100;
}
~Test()
{
delete x;
x=NULL;
cout<<"析构函数正在执行......"<<endl;
}
Test(const Test & t)//这个是浅层复制构造,系统默认会提供,这里写出来便于分析
{
x=t.x;
}
void Display()
{
cout<<"x的值是:"<<*x<<endl;
}
void SetValue(int val)
{
*x=val;
}
private:
int *x;
};
int main()
{
Test *T=new Test;
Test t=*T;
T->Display();
t.Display();

t.SetValue(1);

cout<<"重新设置值后:"<<endl;
T->Display();
t.Display();
return 0;
}

执行结果:



 
 
深层复制构造函数代码
 
#include<iostream>
using namespace std;
class Test
{
public:
Test()
{
x=new int;
*x=100;
}
~Test()
{
delete x;
x=NULL;
cout<<"析构函数正在执行......"<<endl;
}
Test(const Test & t)
{
x=new int;  //为x分配地址空间
*x=*(t.x);  //赋值
}
void Display()
{
cout<<"The value of x:"<<*x<<endl;
}
void SetValue(int val)
{
*x=val;
}
private:
int *x;
};
int main()
{
Test *T = new Test;
Test t = *T;
//Test t;  t=*T 这两条语句不能代替上面Test t = *T;
//因为上面那条语句是初始化,而下面这条语句是赋值,初始化才调用复制构造函数

T->Display();
t.Display();

t.SetValue(1);

cout<<"重新设置值后:"<<endl;
T->Display();
t.Display();
delete T;
return 0;
}


执行结果:



 
复制构造函数调用的条件有以下几个:
1用类的一个对象初始化该类的另一个对象时
2 如果函数的形参是类的对象,调用函数时,进行形参和实参结合时. 
3 如果函数的返回值是类的对象,函数执行完成返回调用者时.

4需要产生一个临时类对象时。
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++