//浅层复制构造函数代码
#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需要产生一个临时类对象时。