拷贝构造函数、浅拷贝/深拷贝构造函数的应用

一、基本概念
构造函数:属于特殊的类成员函数,为数据成员初始化和分配内存。
拷贝构造函数:属于特殊的构造函数,同一个类的A对象构造和初始化B对象。

二、什么时候用拷贝构造函数?
在C++中,拷贝构造函数将会适用在下面三种情况。
1、一个对象以值传递的方式传入函数。
2、一个对象以值传递的方式从函数返回。
3、一个对象需要通过另一个对象进行初始化。


1、一个对象以值传递的方式传入函数

class Rectangle
{
public:
    Rectangle() //构造函数
    {
    }
    Rectangle(const Rectangle& Other) //拷贝构造函数
    {
        height=Other.height;
        width =Other.width;
    }
    ~Rectangle() //析构函数
    {
    }
private:
    int width;
    int height;
};
//定义一个全局函数Func
void Func(Rectangle Rect)
{
    printf("一个对象以值传递的方式传入函数\n");
}

int main()
{
    Rectangle Rectangle1;
    Func(Rectangle1);
    return 0;
}

2、一个对象以值传递的方式从函数返回

class Rectangle
{
public:
    Rectangle(int a,int b) //构造函数
    {
        width = a;
        height = b;
    }
    Rectangle(const Rectangle& Other) //拷贝构造函数
    {
        height=Other.height;
        width =Other.width;
    }
    ~Rectangle() //析构函数
    {
    }
public:
    int width;
    int height;
};
//定义一个全局函数Func
Rectangle Func()
{
    Rectangle Rect(5,3);
    printf("width:%d,height:%d\n",Rect.width,Rect.height);
    return Rect;
}

int main()
{
    Func();
    return 0;
}

3、一个对象需要通过另一个对象进行初始化

class Rectangle
{
public:
    Rectangle(int a,int b) //构造函数
    {
        width = a;
        height = b;
    }
    Rectangle(const Rectangle& Other) //拷贝构造函数
    {
        height=Other.height;
        width =Other.width;
    }
    ~Rectangle() //析构函数
    {
    }
private:
    int width;
    int height;
};

int main()
{
    Rectangle Rectangle1(5,3);
    Rectangle Rectangle2(Rectangle1);
    return 0;
}

三、浅拷贝/深拷贝
1、浅拷贝
如果在类中没有声明拷贝构造函数时,编译器会自动生成一个默认的拷贝构造函数。如果类中无指针等动态成员时,我们自定义的拷贝构造函数通常为浅拷贝。

2、深拷贝
类中有指针等动态成员时,就不能简单地赋值了,而应重新动态分配空间。
原因在于:当类中使用了指针时,两个对象的析构函数将对p指向的同一块内存空间释放两次,导致运行错误(编译器调用一次构造函数,两次析构函数)。
解决办法就是使用深拷贝,将指针P的地址重新动态分配,但保留指针指向相同的数值。

class Rectangle
{
public:
    Rectangle() //构造函数
    {
        p = new int(100);
    }
    Rectangle(const Rectangle& Other) //拷贝构造函数
    {
        height=Other.height;
        width =Other.width;
        p = new int;  //重新动态分配内存
        *p = *(Other.p);
    }
    ~Rectangle() //析构函数
    {
        if (p !=NULL)
        {
            delete p;
        }
    }
private:
    int width;
    int height;
    int *p;
};


int main()
{
    Rectangle Rectangle1;
    Rectangle Rectangle2(Rectangle1);
    return 0;
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值