//***** 浅层复制构造函数 *****
class Person
{
public:
Person(){};
Person(Person &one) // 自定义浅层复制构造函数,就是复制一个对象,说到底,就是复制传进来的对象的所有成员变量,实际上,系统的默认浅层复制构造函数也是类似这样的原理
{
height = one.height; // 关键是在这里进行:指针复制
weight = one.weight;
}
~Person(){};
void SetHeight(int h)
{
height = h;
}
int GetHeight()
{
return height;
}
void SetWeight(int w)
{
weight = w;
}
int GetWeight()
{
return weight;
}
private:
int height;
int weight;
};
//***** 浅层复制构造函数原理 *****
void test1()
{
Person a;
std::cout << "构造一个类Person的对象a" << std::endl;
a.SetHeight(180);
a.SetWeight(130);
std::cout << "a的身高:" << a.GetHeight() << std::endl;
std::cout << "a的体重:" << a.GetWeight() << std::endl;
std::cout << "********************" << std::endl;
std::cout << "复制一个类Person的对象b" << std::endl;
Person b(a); // 声明一个类Person的对象b,把上面定义的对象a传进去,这样就会调用复制构造函数,这样也叫浅层复制构造函数
std::cout << "b的身高:" << b.GetHeight() << std::endl;
std::cout << "b的体重:" << b.GetWeight() << std::endl;
/*
复制构造函数工作原理详细讲解:
首先将对象a作为参数传递到复制构造函数中,然后将对象a的指针成员变量height和weight都复制到对象b中
这样,两个对象的指针height和weight都指向同一内存区域。
*/
}
//***** 深层复制构造函数 *****
class Cube
{
public:
Cube()
{
width = new int;
height = new int;
}
~Cube()
{
delete(width);
delete(height);
width = NULL;
height = NULL;
}
Cube(const Cube &cube) // 自定义深层复制构造函数
{
std::cout << "深层复制构造函数" << std::endl;
width = new int;
height = new int;
*width = *(cube.width);
*height = *(cube.height);
}
void SetWidth(int w)
{
*width = w;
}
int GetWidth()
{
return *width;
}
void SetHeight(int h)
{
*height = h;
}
int GetHeight()
{
return *height;
}
private:
int *width;
int *height;
};
//***** 深层复制构造函数原理 *****
void test2()
{
Cube a;
a.SetWidth(10);
a.SetHeight(20);
std::cout << "a的宽度:" << a.GetWidth() << std::endl;
std::cout << "a的高度:" << a.GetHeight() << std::endl;
Cube b(a);
std::cout << "b的宽度:" << b.GetWidth() << std::endl;
std::cout << "b的高度:" << b.GetHeight() << std::endl;
std::cout << "修改a的成员变量" << std::endl;
a.SetWidth(15);
a.SetHeight(25);
std::cout << "a的宽度:" << a.GetWidth() << std::endl;
std::cout << "a的高度:" << a.GetHeight() << std::endl;
std::cout << "b的宽度:" << b.GetWidth() << std::endl;
std::cout << "b的高度:" << b.GetHeight() << std::endl;
std::cout << "修改b的成员变量" << std::endl;
b.SetWidth(20);
b.SetHeight(30);
std::cout << "a的宽度:" << a.GetWidth() << std::endl;
std::cout << "a的高度:" << a.GetHeight() << std::endl;
std::cout << "b的宽度:" << b.GetWidth() << std::endl;
std::cout << "b的高度:" << b.GetHeight() << std::endl;
/*
注意:不管是浅层复制,还是深层复制,必须是用已有对象创建新对象才会调用复制构造函数,要不然调用的是赋值运算符函数
*/
}
C++_浅层复制构造函数和深层复制构造函数
最新推荐文章于 2021-02-03 20:10:05 发布